Index: sm/trunk/configs/config-altix64-castor.sh
===================================================================
--- /issm/trunk/configs/config-altix64-castor.sh	(revision 15395)
+++ 	(revision )
@@ -1,3 +1,0 @@
-#!/bin/csh
-
-./configure --prefix=$ISSM_DIR --with-serial=no --with-metis-dir=$ISSM_DIR/externalpackages/metis/install --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install --with-mpi-include=/usr/include  --with-mpi-lib="-L/usr/lib -lmpi" --with-petsc-arch=$ISSM_ARCH --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install --with-mkl-dir=/opt/intel/mkl/9.1.023/lib/64 --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/$ISSM_ARCH -lPLAPACK" --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/$ISSM_ARCH/INCLUDE" --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/$ISSM_ARCH/ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/$ISSM_ARCH/ --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/$ISSM_ARCH --with-graphics-lib=/usr/X11R6/lib/libX11.so
Index: /issm/trunk/configs/config-arm-linux.sh
===================================================================
--- /issm/trunk/configs/config-arm-linux.sh	(revision 15395)
+++ /issm/trunk/configs/config-arm-linux.sh	(revision 15396)
@@ -2,14 +2,14 @@
 
 ./configure \
-	--prefix=$ISSM_DIR \
-    --build="i386-apple-darwin10.8.0" \
-    --host="arm-linux-androideabi" \
-    --enable-shared \
-    --with-android=jni \
-	--with-android-ndk=$ISSM_DIR/externalpackages/android/android-ndk/install \
-    --without-fortran \
-	--without-wrappers \
-	--without-kriging \
-	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
-    --disable-static
+   --prefix=$ISSM_DIR\
+   --libdir=$ISSM_DIR/src/mobile/android/ISSM_APP/libs/armeabi\
+   --build="i386-apple-darwin10.8.0"\
+   --host="arm-linux-androideabi"\
+   --enable-shared\
+   --with-android=jni\
+   --with-android-ndk=$ISSM_DIR/externalpackages/android/android-ndk/install\
+   --without-fortran\
+   --without-wrappers\
+   --without-kriging\
+   --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
+   --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install\
Index: sm/trunk/configs/config-cosmos.sh
===================================================================
--- /issm/trunk/configs/config-cosmos.sh	(revision 15395)
+++ 	(revision )
@@ -1,3 +1,0 @@
-#!/bin/csh
-
-./configure --prefix=$ISSM_DIR --with-serial=no --with-metis-dir=$ISSM_DIR/externalpackages/metis/install --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install --with-mpi-include=/opt/mpich/gm/intel10.1/include  --with-mpi-lib="-L/opt/mpich/gm/intel10.1/lib -lmpich -L/usr/local/gm/lib/ -lgm  -lpthread  -lrt" --with-petsc-arch=$ISSM_ARCH --with-mkl-dir=/opt/intel/mkl/10.0.5.025/lib/32/  --with-plapack-dir="-L$ISSM_DIR/externalpackages/petsc/install/$ISSM_ARCH -lPLAPACK" --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/$ISSM_ARCH/INCLUDE" --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/$ISSM_ARCH/ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/$ISSM_ARCH/ --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/$ISSM_ARCH  --with-vendor=intel-linux --with-graphics-lib=/usr/X11R6/lib/libX11.so
Index: /issm/trunk/configs/config-discover.sh
===================================================================
--- /issm/trunk/configs/config-discover.sh	(revision 15395)
+++ /issm/trunk/configs/config-discover.sh	(revision 15396)
@@ -13,5 +13,5 @@
  --with-mkl-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
  --with-mpi-include="/usr/local/intel/mpi/4.0.3.008/include64/" \
- --with-mpi-lib="-L/usr/local/intel/mpi/4.0.3.008/lib64/ -lmpi -lmpiif" \
+ --with-mpi-libflags="-L/usr/local/intel/mpi/4.0.3.008/lib64/ -lmpi -lmpiif" \
  --with-petsc-arch=$ISSM_ARCH \
  --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
Index: /issm/trunk/configs/config-greenplanet.sh
===================================================================
--- /issm/trunk/configs/config-greenplanet.sh	(revision 15395)
+++ /issm/trunk/configs/config-greenplanet.sh	(revision 15396)
@@ -12,5 +12,5 @@
  --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
  --with-mpi-include="/sopt/mpi/openmpi-1.5.4_psm/intel/include/" \
- --with-mpi-lib="-L/sopt/mpi/openmpi-1.5.4_psm/intel/lib/ -lmpi -lmpi_f77" \
+ --with-mpi-libflags="-L/sopt/mpi/openmpi-1.5.4_psm/intel/lib/ -lmpi -lmpi_f77" \
  --with-petsc-arch=$ISSM_ARCH \
  --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
Index: /issm/trunk/configs/config-hoffman2.sh
===================================================================
--- /issm/trunk/configs/config-hoffman2.sh	(revision 15395)
+++ /issm/trunk/configs/config-hoffman2.sh	(revision 15396)
@@ -7,5 +7,5 @@
  --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
  --with-mpi-include=/u/local/intel/11.1/openmpi/1.4.5/include \
- --with-mpi-lib="-L/u/local/intel/11.1/openmpi/1.4.5/include -lmpi" \
+ --with-mpi-libflags="-L/u/local/intel/11.1/openmpi/1.4.5/include -lmpi" \
  --with-petsc-arch=$ISSM_ARCH \
  --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
Index: /issm/trunk/configs/config-ios-linux.sh
===================================================================
--- /issm/trunk/configs/config-ios-linux.sh	(revision 15396)
+++ /issm/trunk/configs/config-ios-linux.sh	(revision 15396)
@@ -0,0 +1,28 @@
+#!/bin/sh
+
+export DEVROOT="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/"
+export SDKROOT="$DEVROOT/SDKs/iPhoneOS6.0.sdk/"
+export CC=$DEVROOT/usr/bin/gcc
+export LD=$DEVROOT/usr/bin/ld
+export CPP=$DEVROOT/usr/bin/cpp
+export CXX=$DEVROOT/usr/bin/g++
+export CXXFLAGS="-O -arch armv7 -isysroot $SDKROOT" 
+export CFLAGS="-O -arch armv7 -isysroot $SDKROOT"
+export AR=$DEVROOT/usr/bin/ar
+export AS=$DEVROOT/usr/bin/as
+export LDFLAGS="-lstdc++ -arch armv7 -isysroot $SDKROOT" 
+export LIBTOOL=$DEVROOT/usr/bin/libtool
+export STRIP=$DEVROOT/usr/bin/strip
+export RANLIB=$DEVROOT/usr/bin/ranlib
+
+./configure \
+	--prefix=$ISSM_DIR \
+    --build="i386-apple-darwin10.8.0" \
+    --host="arm-apple-darwin10" \
+    --enable-shared \
+    --with-ios=yes \
+    --without-fortran \
+	--without-wrappers \
+	--without-kriging \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: sm/trunk/configs/config-linux64-astrid-ad.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid-ad.sh	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-#!/bin/sh
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--without-kriging  \
-	--without-kml  \
-	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
-	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
-	--with-adolc-version=3 \
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: sm/trunk/configs/config-linux64-astrid-mpich1.0.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid-mpich1.0.sh	(revision 15395)
+++ 	(revision )
@@ -1,31 +1,0 @@
-#!/bin/sh
-
-#External packages versions:
-#petsc 3.1 or 3.2
-#mpich 1.0.2
-
-./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-tao-dir=$ISSM_DIR/externalpackages/tao/install \
- --with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
- --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich " \
- --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/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-redhat-linux/4.1.1/ -lgfortran" \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-march=opteron -O2" \
- --with-numthreads=32 \
- --enable-debugging
Index: sm/trunk/configs/config-linux64-astrid-petsc2.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid-petsc2.sh	(revision 15395)
+++ 	(revision )
@@ -1,7 +1,0 @@
-#!/bin/sh
-
-#External packages versions:
-#petsc 2.6
-#mpich 1.0.2
-
-./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/mpich2/install/include  --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich" --with-petsc-arch=$ISSM_ARCH --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install/externalpackages/fblaslapack/$ISSM_ARCH --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/$ISSM_ARCH -lPLAPACK" --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/$ISSM_ARCH/INCLUDE" --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/externalpackages/blacs-dev/$ISSM_ARCH --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/externalpackages/SCALAPACK/$ISSM_ARCH --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/externalpackages/MUMPS_4.6.3/$ISSM_ARCH --with-fortran-lib="-L/usr/lib/gcc/x86_64-redhat-linux/4.1.1/ -lgfortran" --with-graphics-lib=/usr/lib64/libX11.so --with-cxxoptflags="-march=opteron -O2" --with-numthreads=32 --with-scotch-dir=$ISSM_DIR/externalpackages/scotch/install --with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install --enable-debugging --with-shapelib-dir=$ISSM_DIR/externalpackages/shapelib/install\
Index: sm/trunk/configs/config-linux64-astrid-petsc3.3.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid-petsc3.3.sh	(revision 15395)
+++ 	(revision )
@@ -1,33 +1,0 @@
-#!/bin/sh
-
-#External packages versions:
-#petsc 3.3
-#mpich 1.4
-
-./configure \
- --prefix=$ISSM_DIR \
- --with-matlab-dir=$MATLAB_DIR \
- --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
- --with-metis-dir=$ISSM_DIR/externalpackages/petsc/src/externalpackages/metis-5.0.2-p3 \
- --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
- --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
- --with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
- --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich -lmpl " \
- --with-petsc-arch=$ISSM_ARCH \
- --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
- --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/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-redhat-linux/4.1.1/ -lgfortran" \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-march=opteron -O2" \
- --with-numthreads=16 \
- --enable-debugging
- #--with-serial=no \
Index: sm/trunk/configs/config-linux64-astrid-petscdev.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid-petscdev.sh	(revision 15395)
+++ 	(revision )
@@ -1,29 +1,0 @@
-#!/bin/sh
-
-#mpich 1.4
-
-./configure \
- --prefix=$ISSM_DIR \
- --with-matlab-dir=$MATLAB_DIR \
- --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
- --with-metis-dir=$ISSM_DIR/externalpackages/petsc/src/externalpackages/metis-5.0.2-p3 \
- --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
- --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
- --with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include \
- --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich -lmpl " \
- --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-spai-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-hypre-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-superlu-dir=$ISSM_DIR/externalpackages/petsc/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-redhat-linux/4.1.1/ -lgfortran" \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-march=opteron -O3" \
- --with-numthreads=32 \
- --enable-debugging
Index: sm/trunk/configs/config-linux64-astrid.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid.sh	(revision 15395)
+++ 	(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-tao-dir=$ISSM_DIR/externalpackages/tao/install \
- --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
- --with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
- --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/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-redhat-linux/4.1.1/ -lgfortran" \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-march=opteron -O2" \
- --with-numthreads=16 \
- --enable-debugging
Index: /issm/trunk/configs/config-linux64-cloud.sh
===================================================================
--- /issm/trunk/configs/config-linux64-cloud.sh	(revision 15395)
+++ /issm/trunk/configs/config-linux64-cloud.sh	(revision 15396)
@@ -12,6 +12,6 @@
  --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
  --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
- --with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
- --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich -lmpl " \
+ --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+ --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
  --with-petsc-arch=$ISSM_ARCH \
  --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
Index: /issm/trunk/configs/config-linux64-larsen-ad.sh
===================================================================
--- /issm/trunk/configs/config-linux64-larsen-ad.sh	(revision 15396)
+++ /issm/trunk/configs/config-linux64-larsen-ad.sh	(revision 15396)
@@ -0,0 +1,11 @@
+#!/bin/sh
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging  \
+	--without-kml  \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
+	--with-adolc-version=3 \
+	--with-matlab-dir=$MATLAB_DIR \
+	--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 15396)
+++ /issm/trunk/configs/config-linux64-larsen-gia.sh	(revision 15396)
@@ -0,0 +1,33 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 3.4
+#mpich 3.0
+
+./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/petsc/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-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-math77-dir="$ISSM_DIR/externalpackages/math77/install" \
+ --with-gia="yes"\
+ --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-petsc3.2.sh
===================================================================
--- /issm/trunk/configs/config-linux64-larsen-petsc3.2.sh	(revision 15396)
+++ /issm/trunk/configs/config-linux64-larsen-petsc3.2.sh	(revision 15396)
@@ -0,0 +1,34 @@
+#!/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 15396)
+++ /issm/trunk/configs/config-linux64-larsen.sh	(revision 15396)
@@ -0,0 +1,32 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 3.4
+#mpich 3.0
+
+./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/petsc/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-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" \
+ --with-cxxoptflags="-march=opteron -O2" \
+ --with-numthreads=16 \
+ --enable-debugging
Index: /issm/trunk/configs/config-linux64-murdo-nopetsc.sh
===================================================================
--- /issm/trunk/configs/config-linux64-murdo-nopetsc.sh	(revision 15395)
+++ /issm/trunk/configs/config-linux64-murdo-nopetsc.sh	(revision 15396)
@@ -3,6 +3,6 @@
 ./configure \
  --prefix=$ISSM_DIR \
- --with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
- --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich" \
+ --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 \
Index: /issm/trunk/configs/config-linux64-murdo.sh
===================================================================
--- /issm/trunk/configs/config-linux64-murdo.sh	(revision 15395)
+++ /issm/trunk/configs/config-linux64-murdo.sh	(revision 15396)
@@ -9,6 +9,6 @@
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich" \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
Index: /issm/trunk/configs/config-linux64-ubuntu64.sh
===================================================================
--- /issm/trunk/configs/config-linux64-ubuntu64.sh	(revision 15395)
+++ /issm/trunk/configs/config-linux64-ubuntu64.sh	(revision 15396)
@@ -7,6 +7,6 @@
  --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
  --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
- --with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
- --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich -lmpl -ldl" \
+ --with-mpi-include="/usr/lib/mpich/include" \
+ --with-mpi-libflags="-L/usr/lib/mpich/lib -lmpich -lmpl -ldl" \
  --with-petsc-arch=$ISSM_ARCH \
  --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
@@ -19,5 +19,5 @@
  --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
  --with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
- --with-fortran-lib="-lgfortran"\
+ --with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.7/ -lgfortran"\
  --with-numthreads=8 \
  --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
Index: sm/trunk/configs/config-macosx-snowleopard-bothapis.sh
===================================================================
--- /issm/trunk/configs/config-macosx-snowleopard-bothapis.sh	(revision 15395)
+++ 	(revision )
@@ -1,27 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
-	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/include/numpy\
-	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--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 i386 -DMX_COMPAT_32 -O3 -DNDEBUG -w "\
-	--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-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/ 
Index: sm/trunk/configs/config-macosx-snowleopard-python.sh
===================================================================
--- /issm/trunk/configs/config-macosx-snowleopard-python.sh	(revision 15395)
+++ 	(revision )
@@ -1,26 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/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-metis-dir=$ISSM_DIR/externalpackages/metis/install \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--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 -fexceptions -O3 -DNDEBUG -w "\
-	--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-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/ \
Index: sm/trunk/configs/config-macosx32-mathieu.sh
===================================================================
--- /issm/trunk/configs/config-macosx32-mathieu.sh	(revision 15395)
+++ 	(revision )
@@ -1,31 +1,0 @@
-#!/bin/sh
-
-#petsc 3.1 or 3.2
-#mpich 1.4
-
-export FCFLAGS=" -m32"
-export FFLAGS=" -m32"
-export CFLAGS=" -arch i386"
-export CXXFLAGS=" -arch i386"
-
-./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/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/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/lib/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -DMATLAB_MEX_FILE -fno-common -no-cpp-precomp -fexceptions -arch i386  -DMX_COMPAT_32 -O3 -DNDEBUG -w " \
-	--with-numthreads=8
Index: sm/trunk/configs/config-macosx32-ogive.sh
===================================================================
--- /issm/trunk/configs/config-macosx32-ogive.sh	(revision 15395)
+++ 	(revision )
@@ -1,26 +1,0 @@
-#!/bin/sh
-
-#petsc 3.1 or 3.2
-#mpich 1.4
-
-./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/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/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/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 i386 -g -O3 -DNDEBUG -DMX_COMPAT_32" \
-	--with-numthreads=8
Index: sm/trunk/configs/config-macosx64-chris-bothapis.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-chris-bothapis.sh	(revision 15395)
+++ 	(revision )
@@ -1,27 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--with-matlab-dir=$MATLAB_DIR \
-	--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\
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
-	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
-	--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-fortran-lib="/usr/local/gfortran/lib/gcc/x86_64-apple-darwin10/4.6.2/libgfortran.a" \
Index: sm/trunk/configs/config-macosx64-chris-python.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-chris-python.sh	(revision 15395)
+++ 	(revision )
@@ -1,26 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/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-metis-dir=$ISSM_DIR/externalpackages/metis/install \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--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 \
-	--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-numthreads=8
Index: sm/trunk/configs/config-macosx64-chris.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-chris.sh	(revision 15395)
+++ 	(revision )
@@ -1,28 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-./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/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/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-scotch-dir="$ISSM_DIR/externalpackages/scotch/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 -fexceptions -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
-	--with-numthreads=8
Index: sm/trunk/configs/config-macosx64-gsl.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-gsl.sh	(revision 15395)
+++ 	(revision )
@@ -1,8 +1,0 @@
-#!/bin/sh
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--without-wrappers\
-	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install
-	#--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install 
-    #--without-fortran-lib
Index: sm/trunk/configs/config-macosx64-larour-ad.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour-ad.sh	(revision 15395)
+++ 	(revision )
@@ -1,15 +1,0 @@
-#!/bin/sh
-
-pythonversion=2.7
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--without-kriging  \
-	--without-kml  \
-	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
-	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
-	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Library/Frameworks/Python.framework/Versions/$pythonversion/lib/python$pythonversion/site-packages/numpy/core/include/numpy\
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
-
Index: sm/trunk/configs/config-macosx64-larour-nopetsc.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour-nopetsc.sh	(revision 15395)
+++ 	(revision )
@@ -1,12 +1,0 @@
-#!/bin/sh
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
-	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Python.framework/Versions/3.2/lib/python3.2/site-packages/numpy/core/include/numpy\
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
-	--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-gsl-dir=$ISSM_DIR/externalpackages/gsl/install
Index: sm/trunk/configs/config-macosx64-larour-python.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour-python.sh	(revision 15395)
+++ 	(revision )
@@ -1,29 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/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-metis-dir=$ISSM_DIR/externalpackages/metis/install \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
-	--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-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-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
-	#--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
Index: sm/trunk/configs/config-macosx64-larour.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour.sh	(revision 15395)
+++ 	(revision )
@@ -1,29 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-pythonversion=2.7
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
-	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Library/Frameworks/Python.framework/Versions/$pythonversion/lib/python$pythonversion/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/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
-	--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 
Index: sm/trunk/configs/config-macosx64-lion-helene.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-lion-helene.sh	(revision 15395)
+++ 	(revision )
@@ -1,31 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/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-metis-dir=$ISSM_DIR/externalpackages/metis/install \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="-L/usr/X11R6/lib -lX11" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
-	--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-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-numthreads=8
-	#--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
-	#--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
-	#--with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
Index: sm/trunk/configs/config-macosx64-mathieu.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-mathieu.sh	(revision 15395)
+++ 	(revision )
@@ -1,26 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-./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/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/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/lib/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-mlion-mathieu.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-mlion-mathieu.sh	(revision 15395)
+++ 	(revision )
@@ -1,25 +1,0 @@
-#!/bin/sh
-
-#mpich  1.5
-#petsc  3.3
-#python 2.7
-
-./configure \
-	--prefix="$ISSM_DIR" \
-	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
-	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/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-mpi-include="$ISSM_DIR/externalpackages/mpich2/install/include"  \
-	--with-mpi-lib="$ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
-	--with-graphics-lib="-L/usr/X11R6/lib -lX11" \
-	--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-metis-dir="$ISSM_DIR/externalpackages/petsc/src/externalpackages/metis-5.0.2-p3" \
-	--with-numthreads=16
Index: /issm/trunk/configs/config-macosx64-nicole.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-nicole.sh	(revision 15395)
+++ /issm/trunk/configs/config-macosx64-nicole.sh	(revision 15396)
@@ -3,4 +3,5 @@
 #petsc 3.2
 #mpich 1.4
+export F77='/usr/local/gfortran/bin/x86_64-apple-darwin10-gfortran'
 
 ./configure \
@@ -10,6 +11,6 @@
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
+	--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 \
Index: /issm/trunk/configs/config-macosx64-ogive.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-ogive.sh	(revision 15395)
+++ /issm/trunk/configs/config-macosx64-ogive.sh	(revision 15396)
@@ -14,6 +14,6 @@
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
+	--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 \
Index: sm/trunk/configs/config-macosx64-simple.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-simple.sh	(revision 15395)
+++ 	(revision )
@@ -1,23 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-./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-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
-	--with-numthreads=2 \
-	--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/ 
Index: sm/trunk/configs/config-macosx64-sophie.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-sophie.sh	(revision 15395)
+++ 	(revision )
@@ -1,30 +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/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/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="/sw/usr/local/lib/x86_64/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -Wno-write-strings -no-cpp-precomp -fexceptions -arch x86_64 -O3 -DNDEBUG -w "\
-	--with-numthreads=8
Index: /issm/trunk/configs/config-macosx64.sh
===================================================================
--- /issm/trunk/configs/config-macosx64.sh	(revision 15395)
+++ /issm/trunk/configs/config-macosx64.sh	(revision 15396)
@@ -3,27 +3,25 @@
 #petsc 3.2
 #mpich 1.4
-
-pythonversion=2.7
+#python 2.7
 
 ./configure \
 	--prefix=$ISSM_DIR \
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
-	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Library/Frameworks/Python.framework/Versions/$pythonversion/lib/python$pythonversion/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/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
+	--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-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-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
 	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
 	--with-math-lib="/usr/lib/libm.dylib" \
 	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
 	--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-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" 
Index: sm/trunk/configs/config-pleiades-petsc2.sh
===================================================================
--- /issm/trunk/configs/config-pleiades-petsc2.sh	(revision 15395)
+++ 	(revision )
@@ -1,21 +1,0 @@
-#!/bin/csh
-
-./configure \
- --prefix=$ISSM_DIR \
- --with-wrappers=no \
- --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=/nasa/sgi/mpt/1.25/include \
- --with-mpi-lib="-L/nasa/sgi/mpt/1.25/lib/ -lmpi -lpthread -lgfortran" \
- --with-petsc-arch=$ISSM_ARCH \
- --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
- --with-mkl-dir=/nasa/intel/mkl/10.0.011/lib/64/ \
- --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
- --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
- --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-O3 -xS" \
- --with-vendor=intel-pleiades
Index: sm/trunk/configs/config-pleiades-petsc3.3.sh
===================================================================
--- /issm/trunk/configs/config-pleiades-petsc3.3.sh	(revision 15395)
+++ 	(revision )
@@ -1,21 +1,0 @@
-#!/bin/csh
-
-./configure \
- --prefix=$ISSM_DIR \
- --with-wrappers=no \
- --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
- --with-metis-dir=$ISSM_DIR/externalpackages/petsc/src/externalpackages/metis-5.0.2-p3 \
- --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
- --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
- --with-mpi-include=/nasa/sgi/mpt/2.06a67/include \
- --with-mpi-lib="-L/nasa/sgi/mpt/2.06a67/lib/ -lmpi -lpthread -lgfortran " \
- --with-petsc-arch=$ISSM_ARCH \
- --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
- --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
- --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-hypre-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-O3" \
- --with-vendor=intel-pleiades
Index: /issm/trunk/configs/config-pleiades-petsc3.4.sh
===================================================================
--- /issm/trunk/configs/config-pleiades-petsc3.4.sh	(revision 15396)
+++ /issm/trunk/configs/config-pleiades-petsc3.4.sh	(revision 15396)
@@ -0,0 +1,20 @@
+#!/bin/csh
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-wrappers=no \
+ --with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+ --with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-tao-dir="$ISSM_DIR/externalpackages/tao/install" \
+ --with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+ --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-dakota-dir="$ISSM_DIR/externalpackages/dakota/install" \
+ --with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-hypre-dir="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-graphics-lib="/usr/lib64/libX11.so" \
+ --with-cxxoptflags="-O3" \
+ --with-vendor="intel-pleiades"
Index: /issm/trunk/configs/config-pleiades-petscdev.sh
===================================================================
--- /issm/trunk/configs/config-pleiades-petscdev.sh	(revision 15395)
+++ /issm/trunk/configs/config-pleiades-petscdev.sh	(revision 15396)
@@ -9,5 +9,5 @@
  --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
  --with-mpi-include=/nasa/sgi/mpt/2.04/include \
- --with-mpi-lib="-L/nasa/sgi/mpt/2.04/lib/ -lmpi -lpthread -lgfortran" \
+ --with-mpi-libflags="-L/nasa/sgi/mpt/2.04/lib/ -lmpi -lpthread -lgfortran" \
  --with-petsc-arch=$ISSM_ARCH \
  --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
Index: sm/trunk/configs/config-pleiades.sh
===================================================================
--- /issm/trunk/configs/config-pleiades.sh	(revision 15395)
+++ 	(revision )
@@ -1,22 +1,0 @@
-#!/bin/csh
-
-./configure \
- --prefix=$ISSM_DIR \
- --with-wrappers=no \
- --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-tao-dir=$ISSM_DIR/externalpackages/tao/install \
- --with-mpi-include=/nasa/sgi/mpt/1.25/include \
- --with-mpi-lib="-L/nasa/sgi/mpt/1.25/lib/ -lmpi -lpthread -lgfortran" \
- --with-petsc-arch=$ISSM_ARCH \
- --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
- --with-mkl-dir=/nasa/intel/mkl/10.0.011/lib/64/ \
- --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
- --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
- --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-O3 -xS" \
- --with-vendor=intel-pleiades
Index: /issm/trunk/configs/config-walgreen.sh
===================================================================
--- /issm/trunk/configs/config-walgreen.sh	(revision 15396)
+++ /issm/trunk/configs/config-walgreen.sh	(revision 15396)
@@ -0,0 +1,17 @@
+#!/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: sm/trunk/configs/config-win32-eric.sh
===================================================================
--- /issm/trunk/configs/config-win32-eric.sh	(revision 15395)
+++ 	(revision )
@@ -1,6 +1,0 @@
-#!/bin/sh
-
-
-#get configure.sh to pick up the intel compiler 
-
-./configure --prefix=$ISSM_DIR --with-parallel=no --with-vendor=intel-win  --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-petsc-arch=$ISSM_ARCH  --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install/externalpackages/f2cblaslapack/$ISSM_ARCH
Index: /issm/trunk/configs/config-win7-32.sh
===================================================================
--- /issm/trunk/configs/config-win7-32.sh	(revision 15395)
+++ /issm/trunk/configs/config-win7-32.sh	(revision 15396)
@@ -1,16 +1,15 @@
 #!/bin/sh
-
-#Dos style path needed for the windows sdk 7.1 cl compiler: 
-ISSM_DIR_WIN=`cygpath -m "$ISSM_DIR"`
 
 #get configure.sh to pick up the win7 Visual Studio compiler 
 ./configure --prefix=$ISSM_DIR \
-	--with-vendor=intel-win7-32  \
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-triangle-dir="$ISSM_DIR_WIN/externalpackages/triangle/install" \
-	--with-metis-dir="$ISSM_DIR_WIN/externalpackages/metis/install" \
-	--with-petsc-dir="$ISSM_DIR_WIN/externalpackages/petsc/install" \
-	--with-petsc-arch=$ISSM_ARCH  \
-	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install/lib/  \
-	--with-mpi-lib="$ISSM_DIR_WIN/externalpackages/petsc/install/lib/libpetsc.lib" \
-	--with-mpi-include="$ISSM_DIR_WIN/externalpackages/petsc/install/include/mpiuni" 
+   --disable-static \
+   --with-vendor=intel-win7-32  \
+   --with-matlab-dir="$MATLAB_DIR" \
+   --with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+   --with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+   --with-metis-dir="$ISSM_DIR/externalpackages/metis/install" \
+   --with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
+   --with-petsc-arch=$ISSM_ARCH  \
+   --with-mpi-libdir="$ISSM_DIR/externalpackages/petsc/install/lib" \
+   --with-mpi-libflags="-Wl,libpetsc.lib" \
+   --with-mpi-include="$ISSM_DIR/externalpackages/petsc/install/include/mpiuni" 
Index: /issm/trunk/configs/config-win7-64-parallel.sh
===================================================================
--- /issm/trunk/configs/config-win7-64-parallel.sh	(revision 15396)
+++ /issm/trunk/configs/config-win7-64-parallel.sh	(revision 15396)
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+#Dos style path needed for the windows sdk 7.1 cl compiler: 
+ISSM_DIR_WIN=`cygpath -m "$ISSM_DIR"`
+
+#get configure.sh to pick up the win7 Visual Studio compiler 
+./configure --prefix=$ISSM_DIR \
+	--with-vendor=intel-win7-64  \
+	--with-matlab-dir="C:/MATLAB/R2012b/"\
+	--with-triangle-dir="$ISSM_DIR_WIN/externalpackages/triangle/install" \
+	--with-metis-dir="$ISSM_DIR_WIN/externalpackages/metis/install" \
+	--with-petsc-dir="$ISSM_DIR_WIN/externalpackages/petsc/install" \
+	--with-petsc-arch=$ISSM_ARCH  \
+	--with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install/lib"  \
+	--with-mpi-include="C:/MPICH2/include" \
+	--with-mpi-libflags="-LC:/MPICH2/lib mpi.lib"
+
Index: /issm/trunk/configs/config-win7-64.sh
===================================================================
--- /issm/trunk/configs/config-win7-64.sh	(revision 15395)
+++ /issm/trunk/configs/config-win7-64.sh	(revision 15396)
@@ -1,16 +1,15 @@
 #!/bin/sh
-
-#Dos style path needed for the windows sdk 7.1 cl compiler: 
-ISSM_DIR_WIN=`cygpath -m "$ISSM_DIR"`
 
 #get configure.sh to pick up the win7 Visual Studio compiler 
 ./configure --prefix=$ISSM_DIR \
+   --disable-static \
 	--with-vendor=intel-win7-64  \
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-triangle-dir="$ISSM_DIR_WIN/externalpackages/triangle/install" \
-	--with-metis-dir="$ISSM_DIR_WIN/externalpackages/metis/install" \
-	--with-petsc-dir="$ISSM_DIR_WIN/externalpackages/petsc/install" \
+	--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-petsc-arch=$ISSM_ARCH  \
 	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install/lib/  \
-	--with-mpi-lib="$ISSM_DIR_WIN/externalpackages/petsc/install/lib/libpetsc.lib" \
-	--with-mpi-include="$ISSM_DIR_WIN/externalpackages/petsc/install/include/mpiuni" 
+	--with-mpi-libflags-dir="$ISSM_DIR/externalpackages/petsc/install/lib" \
+   --with-mpi-libflagss="-Wl,libpetsc.lib" \
+	--with-mpi-include-dir="$ISSM_DIR/externalpackages/petsc/install/include/mpiuni" 
Index: /issm/trunk/configure.ac
===================================================================
--- /issm/trunk/configure.ac	(revision 15395)
+++ /issm/trunk/configure.ac	(revision 15396)
@@ -2,5 +2,5 @@
 
 #AUTOCONF
-AC_INIT([ISSM],[4.2.5],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_INIT([ISSM],[4.3],[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
@@ -9,7 +9,7 @@
 
 #Compilers
-AC_PROG_CC([cccl cl icl gcc])
+AC_PROG_CC([icc cccl cl icl gcc])
 AC_PROG_CPP
-AC_PROG_CXX([cccl cl icl g++])
+AC_PROG_CXX([icpc cccl cl icl g++])
 AC_PROG_F77([ifort g77 gfortran])
 
@@ -21,5 +21,5 @@
 #Initialize automake and declare foreign so that we don't need a ChangeLog, INSTALL, etc
 AM_INIT_AUTOMAKE([foreign])
-AM_CONFIG_HEADER([./config.h])   #Config file must be config.h
+AC_CONFIG_HEADERS([./config.h])   #Config file must be config.h
 AM_SILENT_RULES([yes])           #Do not show compilation command by default
 AM_PROG_CC_C_O
@@ -39,6 +39,6 @@
 			src/wrappers/python/Makefile
 			src/wrappers/matlab/Makefile
-			src/android/Makefile
-			src/android/ISSM/Makefile
+			src/mobile/Makefile
+			src/mobile/native/Makefile
 			src/m/Makefile])
 
Index: /issm/trunk/etc/environment.csh
===================================================================
--- /issm/trunk/etc/environment.csh	(revision 15395)
+++ /issm/trunk/etc/environment.csh	(revision 15396)
@@ -1,3 +1,3 @@
-#ISSM_DIR and ISSM_ARCH should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
+#ISSM_DIR should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
 
 #Load ISSM scripts
@@ -25,5 +25,5 @@
 if (-d $PETSC_DIR) then
 	setenv PETSC_DIR {$PETSC_DIR}
-	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$PETSC_DIR/lib/{$ISSM_ARCH}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$PETSC_DIR/lib
 endif
 
@@ -31,5 +31,5 @@
 set SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
 if (-d $SLEPC_DIR) then
-	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$SLEPC_DIR/lib/{$ISSM_ARCH}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$SLEPC_DIR/lib
 endif
 
@@ -37,5 +37,5 @@
 set TAO_DIR="$ISSM_DIR/externalpackages/tao/install"
 if (-d $TAO_DIR) then
-	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$TAO_DIR/lib/{$ISSM_ARCH}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$TAO_DIR/lib
 endif
 
Index: /issm/trunk/etc/environment.sh
===================================================================
--- /issm/trunk/etc/environment.sh	(revision 15395)
+++ /issm/trunk/etc/environment.sh	(revision 15396)
@@ -65,4 +65,5 @@
 libpathappend "$MATLAB_DIR/lib"
 
+#legacy mpich2 (To be removed)
 MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
 if [ -d "$MPI_DIR" ]; then
@@ -72,4 +73,11 @@
 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
@@ -77,5 +85,5 @@
 
 SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
-libpathappend "$SLEPC_DIR/lib/$ISSM_ARCH"
+libpathappend "$SLEPC_DIR/lib"
 
 TAO_DIR="$ISSM_DIR/externalpackages/tao/install"
@@ -84,4 +92,5 @@
 DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
 pathappend "$DAKOTA_DIR/bin"
+libpathappend "$DAKOTA_DIR/lib"
 
 DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
@@ -106,4 +115,7 @@
 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"
@@ -178,5 +190,5 @@
 
 CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
-pathappend "$CMAKE_DIR/bin"
+pathprepend "$CMAKE_DIR/bin"
 
 SHAPELIB_DIR="$ISSM_DIR/externalpackages/shapelib/install"
@@ -229,32 +241,32 @@
 
 HDF5_DIR="$ISSM_DIR/externalpackages/hdf5/install"
+dylibpathappend "$HDF5_DIR/lib"
+libpathappend "$HDF5_DIR/lib"
 if [ -d "$HDF5_DIR" ]; then
-	dylibpathappend "$HDF5_DIR/lib"
-	libpathappend "$HDF5_DIR/lib"
 	export LIBRARY_PATH="$LIBRARY_PATH:$HDF5_DIR/lib"
 	export C_INCLUDE_PATH="$C_INCLUDE_PATH:$HDF5_DIR/include"
 fi
 
-#NETCDF
 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 DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$NETCDF_DIR/lib"
-	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$NETCDF_DIR/lib"
 	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
 
-#SVN
+NETCDF_CXX_DIR="$ISSM_DIR/externalpackages/netcdf-cxx/install"
+libpathappend "$NETCDF_CXX_DIR/lib"
+
 SVN_DIR="$ISSM_DIR/externalpackages/svn/install"
-if [ -d "$SVN_DIR" ]; then
-	pathprepend   "$SVN_DIR/bin"
-	libpathappend "$SVN_DIR/lib"
-fi
+pathprepend   "$SVN_DIR/bin"
+libpathappend "$SVN_DIR/lib"
 
 APR_DIR="$ISSM_DIR/externalpackages/apr/install"
-if [ -d "$APR_DIR" ]; then
-	pathappend    "$APR_DIR/bin"
-	libpathappend "$APR_DIR/lib"
-fi
+pathappend    "$APR_DIR/bin"
+libpathappend "$APR_DIR/lib"
 
 APR_UTIL_DIR="$ISSM_DIR/externalpackages/apr-util/install"
@@ -271,2 +283,5 @@
 SWIG_DIR="$ISSM_DIR/externalpackages/swig/install"
 pathappend   "$SWIG_DIR"
+
+#AUX-CONFIG
+pathappend   "$ISSM_DIR/aux-config"
Index: /issm/trunk/externalpackages/adolc/install-update-dev.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-update-dev.sh	(revision 15395)
+++ /issm/trunk/externalpackages/adolc/install-update-dev.sh	(revision 15396)
@@ -10,5 +10,5 @@
 
 #symlink: 
-ln -s  /u/astrid-r1b/larour/issm-uci/trunk-jpl/externalpackages/adolc/adolc_issm ./adolc_issm
+ln -s /proj/ice/larour2/issm-uci/trunk-jpl/externalpackages/adolc/adolc_issm ./adolc_issm
 
 #update and compile
Index: /issm/trunk/externalpackages/android/android-sdk/install.sh
===================================================================
--- /issm/trunk/externalpackages/android/android-sdk/install.sh	(revision 15395)
+++ /issm/trunk/externalpackages/android/android-sdk/install.sh	(revision 15396)
@@ -19,5 +19,5 @@
 
 	# Cleanup the install
-	rm -rf install-sdk
+	rm -rf install
 
 	# Download from ISSM server
@@ -28,5 +28,5 @@
 
 	# Move to install
-	mv -f android-sdk-macosx install-sdk
+	mv -f android-sdk-macosx install
 
 	# Post_install configuration: 
@@ -39,5 +39,5 @@
 	# Note: API 16, API 15 and 14 correspond to Android 4.1, 4.0.3 and 4.0 respectively. 
 
-	cd install-sdk/tools/ && source ./android update sdk -t platform-tool,${api_levels},system-image --no-ui
+	cd install/tools/ && source ./android update sdk -t platform-tool,${api_levels},system-image --no-ui
 
 fi
@@ -50,5 +50,5 @@
 
 	# Here we delete the Android-4.0.3 device if it already exists.
-	cd $present_dir/install-sdk/tools
+	cd $present_dir/install/tools
 
     if [ -e $ANDROID_DIR/android-emulators/$default_droid ] 
@@ -71,5 +71,5 @@
     # a terminal in our device.
 
-	cd $present_dir/install-sdk/tools
+	cd $present_dir/install/tools
 	./emulator -avd $default_droid -sdcard $ANDROID_DIR/android-emulators/$sd_card.img &
 
@@ -79,4 +79,4 @@
 
 if [[ $step == "4" || $step == "0" ]]; then
-	rm -rf install-sdk
+	rm -rf install
 fi
Index: /issm/trunk/externalpackages/autotools/install-win.sh
===================================================================
--- /issm/trunk/externalpackages/autotools/install-win.sh	(revision 15396)
+++ /issm/trunk/externalpackages/autotools/install-win.sh	(revision 15396)
@@ -0,0 +1,46 @@
+#!/bin/bash
+set -eu
+
+rm -rf install
+mkdir install
+
+export PATH="$ISSM_DIR/externalpackages/autotools/install/bin:$PATH"
+
+#install autoconf
+echo " === INSTALLING AUTOCONF =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/autoconf-2.68.tar.gz' 'autoconf-2.68.tar.gz'
+tar -zxvf autoconf-2.68.tar.gz
+mv autoconf-2.68 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
+
+#install automake
+echo " === INSTALLING AUTOMAKE =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/automake-1.11.3.tar.gz' 'automake-1.11.3.tar.gz'
+tar -zxvf  automake-1.11.3.tar.gz
+mv automake-1.11.3 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
+
+#install libtool
+echo " === INSTALLING LIBTOOL =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libtool-2.4.2.tar.gz' 'libtool-2.4.2.tar.gz'
+tar -zxvf  libtool-2.4.2.tar.gz
+rm libtool-2.4.2.tar.gz
+mv libtool-2.4.2 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
+
+patch ./install/share/aclocal/libtool.m4 < ./patches/libtool.m4.patch
Index: /issm/trunk/externalpackages/autotools/patches/libtool.m4.patch
===================================================================
--- /issm/trunk/externalpackages/autotools/patches/libtool.m4.patch	(revision 15396)
+++ /issm/trunk/externalpackages/autotools/patches/libtool.m4.patch	(revision 15396)
@@ -0,0 +1,38 @@
+--- m4/libtool.m4	2013-06-19 22:19:27.313488900 -0700
++++ m4/libtool.m4.bak	2013-06-18 18:45:55.766285300 -0700
+@@ -4752,7 +4752,7 @@
+       _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
+ 
+       if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
++        _LT_TAGVAR(archive_cmds, $1)='$CC /LD $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib '
+ 	# If the export-symbols file already is a .def file (1st line
+ 	# is EXPORTS), use it as is; otherwise, prepend...
+ 	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+@@ -4761,7 +4761,7 @@
+ 	  echo EXPORTS > $output_objdir/$soname.def;
+ 	  cat $export_symbols >> $output_objdir/$soname.def;
+ 	fi~
+-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
++	$CC /LD $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib '
+       else
+ 	_LT_TAGVAR(ld_shlibs, $1)=no
+       fi
+@@ -6168,7 +6168,7 @@
+ 	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+ 
+ 	  if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
++	    _LT_TAGVAR(archive_cmds, $1)='$CC /LD -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib '
+ 	    # If the export-symbols file already is a .def file (1st line
+ 	    # is EXPORTS), use it as is; otherwise, prepend...
+ 	    _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+@@ -6177,7 +6177,7 @@
+ 	      echo EXPORTS > $output_objdir/$soname.def;
+ 	      cat $export_symbols >> $output_objdir/$soname.def;
+ 	    fi~
+-	    $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
++	    $CC /LD -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib '
+ 	  else
+ 	    _LT_TAGVAR(ld_shlibs, $1)=no
+ 	  fi
Index: /issm/trunk/externalpackages/cccl/issm/cccl
===================================================================
--- /issm/trunk/externalpackages/cccl/issm/cccl	(revision 15395)
+++ /issm/trunk/externalpackages/cccl/issm/cccl	(revision 15396)
@@ -62,5 +62,5 @@
 
 		*.mex*)
-			opts="$opts -o $1"
+			opts="$opts /OUT:$1"
 		;;
 
@@ -86,5 +86,16 @@
 	#do nothing
 	;;
-
+   -I*)
+	   include=`echo $1 | sed 's/-I//g'`
+	   include=`cygpath -m "$include"`
+	   include="/I\"$include\""
+	   includeopts="$includeopts $include"
+   ;;
+	-L*)
+		library=`echo $1 | sed 's/-L//g'`
+		library=`cygpath -m $library`
+		string="/link /LIBPATH:\"$library\""
+		opts="$opts $string"
+	;;
 	*)
 		#do nothing
@@ -97,10 +108,6 @@
 done
 			
-#Some default options:
-opts="$opts /nologo"
-
-#echo "$prog $opts"
-exec $prog $opts
-exit 0
-
-    
+#pass all our processing through the echo command, so we are sure that the string has no quirk, 
+#and that once passed by exec to cl, everything works fine.
+command=`echo "$prog "$includeopts" $opts /nologo"`
+exec $command
Index: sm/trunk/externalpackages/cppcheck/README
===================================================================
--- /issm/trunk/externalpackages/cppcheck/README	(revision 15395)
+++ 	(revision )
@@ -1,2 +1,0 @@
-Cppcheck: static analysis of source code.
-Obtained code from http://sourceforge.net/projects/cppcheck/
Index: /issm/trunk/externalpackages/cppcheck/install-dev.sh
===================================================================
--- /issm/trunk/externalpackages/cppcheck/install-dev.sh	(revision 15396)
+++ /issm/trunk/externalpackages/cppcheck/install-dev.sh	(revision 15396)
@@ -0,0 +1,18 @@
+#!/bin/bash
+set -eu
+
+#Erase install
+rm -rf install  src 
+
+#Download
+git clone git://github.com/danmar/cppcheck.git src
+
+#compile
+cd src
+if [ $# -eq 0 ]; then
+	make 
+else 
+	make -j $1
+fi  
+make install PREFIX=$ISSM_DIR/externalpackages/cppcheck/install
+cd ..
Index: /issm/trunk/externalpackages/cython/install.sh
===================================================================
--- /issm/trunk/externalpackages/cython/install.sh	(revision 15396)
+++ /issm/trunk/externalpackages/cython/install.sh	(revision 15396)
@@ -0,0 +1,13 @@
+#!/bin/bash
+set -eu
+
+#clean up
+rm -rf Cython-0.18
+
+#download numpy first
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Cython-0.18.tar.gz' 'cython.tar.gz'
+
+#install numpy
+tar -zxvf cython.tar.gz
+cd Cython-0.18
+python setup.py install
Index: sm/trunk/externalpackages/dakota/README
===================================================================
--- /issm/trunk/externalpackages/dakota/README	(revision 15395)
+++ 	(revision )
@@ -1,9 +1,0 @@
-version 4.3 of dakota is not yet released. The 4.3 version 
-here refers to the VOTD release on May 12th 2009. While waiting 
-for 4.3, we consider the develpment version to be 4.3.
-4.2 is replaced by 4.3, to handle fnEvalId extra arguemnt to the Dakota 
-structure.
-
-Be sure to set FC and F77 variable names to point to your fortran compiler, otherwise, 
-	the LHS packages will pick up gfortran as its fortran compiler, which can create serious 
-	troubles.
Index: /issm/trunk/externalpackages/dakota/configs/5.2/Teuchos_ConfigDefs.hpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.2/Teuchos_ConfigDefs.hpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.2/Teuchos_ConfigDefs.hpp.patch	(revision 15396)
@@ -0,0 +1,2 @@
+87a88
+> #include <stddef.h>
Index: /issm/trunk/externalpackages/dakota/configs/5.3.1/BuildDakotaCustom.cmake.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3.1/BuildDakotaCustom.cmake.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3.1/BuildDakotaCustom.cmake.patch	(revision 15396)
@@ -0,0 +1,26 @@
+64,65c64,65
+< #set( DAKOTA_HAVE MPI ON
+< #     CACHE BOOL "Build with MPI enabled" FORCE)
+---
+> set( DAKOTA_HAVE MPI OFF
+>      CACHE BOOL "Build with MPI disabled" FORCE)
+73,77c73,77
+< #set(BOOST_ROOT
+< #    "path/to/custom/Boost/install/directory"
+< #    CACHE PATH "Use non-standard Boost install" FORCE)
+< #set( Boost_NO_SYSTEM_PATHS TRUE
+< #     CACHE BOOL "Supress search paths other than BOOST_ROOT" FORCE)
+---
+> set(BOOST_ROOT
+>     "$ENV{ISSM_DIR}/externalpackages/boost/install"
+>     CACHE PATH "Use non-standard Boost install" FORCE)
+> set( Boost_NO_SYSTEM_PATHS TRUE
+>      CACHE BOOL "Supress search paths other than BOOST_ROOT" FORCE)
+91,93c91,93
+< #set( CMAKE_INSTALL_PREFIX
+< #     "/path/to/Dakota/installation"
+< #     CACHE PATH "Path to Dakota installation" )
+---
+> set( CMAKE_INSTALL_PREFIX
+>      "$ENV{ISSM_DIR}/externalpackages/dakota/install"
+>      CACHE PATH "Path to Dakota installation" )
Index: /issm/trunk/externalpackages/dakota/configs/5.3.1/DakotaDev.cmake.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3.1/DakotaDev.cmake.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3.1/DakotaDev.cmake.patch	(revision 15396)
@@ -0,0 +1,16 @@
+4,8c4,8
+< set(DAKOTA_HAVE_MPI TRUE CACHE BOOL "Enable MPI in DAKOTA?")
+< set(ENABLE_DAKOTA_DOCS TRUE CACHE BOOL "Enable DAKOTA documentation build")
+< set(ENABLE_SPEC_MAINT TRUE CACHE BOOL 
+<   "Enable DAKOTA specification maintenance mode?")
+< set(PECOS_ENABLE_TESTS TRUE CACHE BOOL "Enable Pecos-specific tests?")
+---
+> #set(DAKOTA_HAVE_MPI TRUE CACHE BOOL "Enable MPI in DAKOTA?")
+> #set(ENABLE_DAKOTA_DOCS TRUE CACHE BOOL "Enable DAKOTA documentation build")
+> #set(ENABLE_SPEC_MAINT TRUE CACHE BOOL 
+> #  "Enable DAKOTA specification maintenance mode?")
+> #set(PECOS_ENABLE_TESTS TRUE CACHE BOOL "Enable Pecos-specific tests?")
+14c14
+< #set(HAVE_X_GRAPHICS OFF CACHE BOOL "Disable dependency on X libraries" FORCE)
+---
+> set(HAVE_X_GRAPHICS OFF CACHE BOOL "Disable dependency on X libraries" FORCE)
Index: /issm/trunk/externalpackages/dakota/configs/5.3.1/NonDLocalReliability.cpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3.1/NonDLocalReliability.cpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3.1/NonDLocalReliability.cpp.patch	(revision 15396)
@@ -0,0 +1,9 @@
+2587a2588
+> 	  // add sensitivity output to importance factors (jes, 8/06/10)
+2592c2593,2596
+< 	    << std::setw(width) << impFactor(j,i) << '\n';
+---
+> 	    << std::setw(width) << impFactor(j,i)
+> 	    << "  Sensitivity = "
+> 	    << std::resetiosflags(std::ios::adjustfield)
+> 	    << std::setw(width) << fnGradsMeanX(j,i) << '\n';
Index: /issm/trunk/externalpackages/dakota/configs/5.3.1/NonDSampling.cpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3.1/NonDSampling.cpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3.1/NonDSampling.cpp.patch	(revision 15396)
@@ -0,0 +1,25 @@
+703,709c703,710
+<   if (!subIteratorFlag) {
+<     nonDSampCorr.compute_correlations(vars_samples, resp_samples);
+<     // archive the correlations to the results DB
+<     nonDSampCorr.archive_correlations(run_identifier(), resultsDB,
+< 				      cv_labels, div_labels, drv_labels,
+< 				      iteratedModel.response_labels());
+<   }
+---
+> //don't compute for now, too expensive.
+> //  if (!subIteratorFlag) {
+> //    nonDSampCorr.compute_correlations(vars_samples, resp_samples);
+> //    // archive the correlations to the results DB
+> //    nonDSampCorr.archive_correlations(run_identifier(), resultsDB,
+> //				      cv_labels, div_labels, drv_labels,
+> //				      iteratedModel.response_labels());
+> //  }
+1196,1197c1197,1200
+<     nonDSampCorr.print_correlations(s, cv_labels, div_labels, drv_labels,
+< 				    iteratedModel.response_labels());
+---
+> 
+> //don't output for now.
+> //    nonDSampCorr.print_correlations(s, cv_labels, div_labels, drv_labels,
+> //				    iteratedModel.response_labels());
Index: /issm/trunk/externalpackages/dakota/configs/5.3.1/ParallelLibrary.cpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3.1/ParallelLibrary.cpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3.1/ParallelLibrary.cpp.patch	(revision 15396)
@@ -0,0 +1,40 @@
+107a108
+>   initialized=0; //we run serially all the time!
+133a135
+>   initialized=0; //we run serially all the time!
+141a144,176
+> /** 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),
+>   mpirunFlag(false), ownMPIFlag(false), dummyFlag(false),
+>   stdOutputToFile(false), stdErrorToFile(false), checkFlag(false),
+>   preRunFlag(true), runFlag(true), postRunFlag(true), userModesFlag(false),
+>   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
+> 
+>   // do not initialize MPI.  Get worldRank/worldSize if available
+>   ParallelLevel pl;
+> #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.";
+> #else // mpi not available
+>   pl.serverIntraComm = MPI_COMM_NULL;
+>   Cout << "Running Dakota 5.3.1 serial executable in serial mode for ISSM.\n";
+> #endif // HAVE_MPI
+> 
+>   parallelLevels.push_back(pl);
+>   currPLIter = parallelLevels.begin();
+>   increment_parallel_configuration();
+> }
+> 
+> 
+1536a1572
+>   initialized=0; //we run serially all the time!
Index: /issm/trunk/externalpackages/dakota/configs/5.3.1/ParallelLibrary.hpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3.1/ParallelLibrary.hpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3.1/ParallelLibrary.hpp.patch	(revision 15396)
@@ -0,0 +1,3 @@
+358a359,360
+>   /// library mode constructor, serial mode (for the ISSM software)
+>   ParallelLibrary(char* serial_mode);
Index: /issm/trunk/externalpackages/dakota/configs/5.3.1/pecos_global_defs.hpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3.1/pecos_global_defs.hpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3.1/pecos_global_defs.hpp.patch	(revision 15396)
@@ -0,0 +1,4 @@
+25a26
+> #ifndef PI
+26a28
+> #endif
Index: /issm/trunk/externalpackages/dakota/configs/5.3/BuildDakotaCustom.cmake.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3/BuildDakotaCustom.cmake.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3/BuildDakotaCustom.cmake.patch	(revision 15396)
@@ -0,0 +1,40 @@
+41,46c41,46
+< #set( BLAS_LIBS 
+< #      "/usr/lib64"
+< #      CACHE FILEPATH "Use non-standard BLAS library path" FORCE )
+< #set( LAPACK_LIBS 
+< #      "/usr/lib64"
+< #      CACHE FILEPATH "Use non-standard BLAS library path" FORCE )
+---
+> set( BLAS_LIBS 
+>       "/usr/lib64/libblas.so.3.0.3"
+>       CACHE FILEPATH "Use non-standard BLAS library path" FORCE )
+> set( LAPACK_LIBS 
+>       "/usr/lib64/liblapack.so.3.0.3"
+>       CACHE FILEPATH "Use non-standard BLAS library path" FORCE )
+64,65c64,65
+< #set( DAKOTA_HAVE MPI ON
+< #     CACHE BOOL "Build with MPI enabled" FORCE)
+---
+> set( DAKOTA_HAVE MPI OFF
+>      CACHE BOOL "Build with MPI disabled" FORCE)
+73,77c73,77
+< #set(BOOST_ROOT
+< #    "path/to/custom/Boost/install/directory"
+< #    CACHE PATH "Use non-standard Boost install" FORCE)
+< #set( Boost_NO_SYSTEM_PATHS TRUE
+< #     CACHE BOOL "Supress search paths other than BOOST_ROOT" FORCE)
+---
+> set(BOOST_ROOT
+>     "$ENV{ISSM_DIR}/externalpackages/boost/install"
+>     CACHE PATH "Use non-standard Boost install" FORCE)
+> set( Boost_NO_SYSTEM_PATHS TRUE
+>      CACHE BOOL "Supress search paths other than BOOST_ROOT" FORCE)
+91,93c91,93
+< #set( CMAKE_INSTALL_PREFIX
+< #     "/path/to/Dakota/installation"
+< #     CACHE PATH "Path to Dakota installation" )
+---
+> set( CMAKE_INSTALL_PREFIX
+>      "$ENV{ISSM_DIR}/externalpackages/dakota/install"
+>      CACHE PATH "Path to Dakota installation" )
Index: /issm/trunk/externalpackages/dakota/configs/5.3/DakotaDev.cmake.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3/DakotaDev.cmake.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3/DakotaDev.cmake.patch	(revision 15396)
@@ -0,0 +1,14 @@
+4,7c4,7
+< set(DAKOTA_HAVE_MPI TRUE CACHE BOOL "Enable MPI in DAKOTA?")
+< set(ENABLE_DAKOTA_DOCS TRUE CACHE BOOL "Enable DAKOTA documentation build")
+< set(ENABLE_SPEC_MAINT TRUE CACHE BOOL 
+<   "Enable DAKOTA specification maintenance mode?")
+---
+> #set(DAKOTA_HAVE_MPI TRUE CACHE BOOL "Enable MPI in DAKOTA?")
+> #set(ENABLE_DAKOTA_DOCS TRUE CACHE BOOL "Enable DAKOTA documentation build")
+> #set(ENABLE_SPEC_MAINT TRUE CACHE BOOL 
+> #  "Enable DAKOTA specification maintenance mode?")
+13c13
+< #set(HAVE_X_GRAPHICS OFF CACHE BOOL "Disable dependency on X libraries" FORCE)
+---
+> set(HAVE_X_GRAPHICS OFF CACHE BOOL "Disable dependency on X libraries" FORCE)
Index: /issm/trunk/externalpackages/dakota/configs/5.3/NonDLocalReliability.cpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3/NonDLocalReliability.cpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3/NonDLocalReliability.cpp.patch	(revision 15396)
@@ -0,0 +1,9 @@
+2579a2580
+> 	  // add sensitivity output to importance factors (jes, 8/06/10)
+2584c2585,2588
+< 	    << std::setw(width) << impFactor(j,i) << '\n';
+---
+> 	    << std::setw(width) << impFactor(j,i)
+> 	    << "  Sensitivity = "
+> 	    << std::resetiosflags(std::ios::adjustfield)
+> 	    << std::setw(width) << fnGradsMeanX(j,i) << '\n';
Index: /issm/trunk/externalpackages/dakota/configs/5.3/NonDSampling.cpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3/NonDSampling.cpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3/NonDSampling.cpp.patch	(revision 15396)
@@ -0,0 +1,25 @@
+703,709c703,710
+<   if (!subIteratorFlag) {
+<     nonDSampCorr.compute_correlations(vars_samples, resp_samples);
+<     // archive the correlations to the results DB
+<     nonDSampCorr.archive_correlations(run_identifier(), resultsDB,
+< 				      cv_labels, div_labels, drv_labels,
+< 				      iteratedModel.response_labels());
+<   }
+---
+> //don't compute for now, too expensive.
+> //  if (!subIteratorFlag) {
+> //    nonDSampCorr.compute_correlations(vars_samples, resp_samples);
+> //    // archive the correlations to the results DB
+> //    nonDSampCorr.archive_correlations(run_identifier(), resultsDB,
+> //				      cv_labels, div_labels, drv_labels,
+> //				      iteratedModel.response_labels());
+> //  }
+1196,1197c1197,1200
+<     nonDSampCorr.print_correlations(s, cv_labels, div_labels, drv_labels,
+< 				    iteratedModel.response_labels());
+---
+> 
+> //don't output for now.
+> //    nonDSampCorr.print_correlations(s, cv_labels, div_labels, drv_labels,
+> //				    iteratedModel.response_labels());
Index: /issm/trunk/externalpackages/dakota/configs/5.3/ParallelLibrary.cpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3/ParallelLibrary.cpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3/ParallelLibrary.cpp.patch	(revision 15396)
@@ -0,0 +1,40 @@
+103a104
+>   initialized=0; //we run serially all the time!
+129a131
+>   initialized=0; //we run serially all the time!
+137a140,172
+> /** 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),
+>   mpirunFlag(false), ownMPIFlag(false), dummyFlag(false),
+>   stdOutputToFile(false), stdErrorToFile(false), checkFlag(false),
+>   preRunFlag(true), runFlag(true), postRunFlag(true), userModesFlag(false),
+>   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
+> 
+>   // do not initialize MPI.  Get worldRank/worldSize if available
+>   ParallelLevel pl;
+> #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 MPI executable in serial mode on CPU 0 for ISSM.";
+> #else // mpi not available
+>   pl.serverIntraComm = MPI_COMM_NULL;
+>   Cout << "Running Dakota 5.3 serial executable in serial mode for ISSM.\n";
+> #endif // HAVE_MPI
+> 
+>   parallelLevels.push_back(pl);
+>   currPLIter = parallelLevels.begin();
+>   increment_parallel_configuration();
+> }
+> 
+> 
+1517a1553
+>   initialized=0; //we run serially all the time!
Index: /issm/trunk/externalpackages/dakota/configs/5.3/ParallelLibrary.hpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3/ParallelLibrary.hpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3/ParallelLibrary.hpp.patch	(revision 15396)
@@ -0,0 +1,3 @@
+358a359,360
+>   /// library mode constructor, serial mode (for the ISSM software)
+>   ParallelLibrary(char* serial_mode);
Index: /issm/trunk/externalpackages/dakota/configs/5.3/pecos_global_defs.hpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3/pecos_global_defs.hpp.patch	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3/pecos_global_defs.hpp.patch	(revision 15396)
@@ -0,0 +1,4 @@
+25a26
+> #ifndef PI
+26a28
+> #endif
Index: /issm/trunk/externalpackages/dakota/configs/5.3/utilibExpat_patch.txt
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3/utilibExpat_patch.txt	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/configs/5.3/utilibExpat_patch.txt	(revision 15396)
@@ -0,0 +1,58 @@
+Index: CMakeLists.txt
+===================================================================
+--- CMakeLists.txt	(revision 1968)
++++ CMakeLists.txt	(working copy)
+@@ -30,6 +30,17 @@
+ if(UTILIB_YES_MEMDEBUG)
+   add_definitions(-DUTILIB_YES_MEMDEBUG=1)
+ endif()
++option(UTILIB_HAVE_EXPAT "Enable expat in utilib" OFF)
++if (UTILIB_HAVE_EXPAT)
++  find_package(EXPAT)
++  if (EXPAT_FOUND)
++    # Use the same definition as autotools build
++    add_definitions("-DUTILIB_HAVE_EXPAT_H")
++    # TODO: add include path (EXPAT_INCLUDE_DIRS) in relevant subdirs?
++  else()
++    message(WARNING "expat requested, but not found")
++  endif()
++endif()
+ 
+ #inspect the system so that we can generate utilib_config.h 
+ include(CheckFunctionExists)
+@@ -47,7 +58,6 @@
+ CHECK_INCLUDE_FILES("windows.h;dbghelp.h" UTILIB_HAVE_DBGHELP_H)
+ CHECK_INCLUDE_FILE(err.h UTILIB_HAVE_ERR_H)
+ CHECK_INCLUDE_FILE(execinfo.h UTILIB_HAVE_EXECINFO_H)
+-CHECK_INCLUDE_FILE(expat.h UTILIB_HAVE_EXPAT_H)
+ CHECK_INCLUDE_FILE(float.h UTILIB_HAVE_FLOAT_H)
+ CHECK_INCLUDE_FILE(limits.h UTILIB_HAVE_LIMITS_H)
+ CHECK_INCLUDE_FILE(strings.h UTILIB_HAVE_STRINGS_H)
+@@ -57,9 +67,7 @@
+ CHECK_INCLUDE_FILE(values.h UTILIB_HAVE_VALUES_H)
+ CHECK_INCLUDE_FILE(windows.h UTILIB_HAVE_WINDOWS_H)
+ 
+-find_library(EXPAT_LIB expat)
+ 
+-
+ # Use common HAVE_BOOST to indicate usage of Boost across packages
+ # Ultimately need to #define UTILIB_HAVE_BOOST if used 
+ set(HAVE_BOOST OFF CACHE BOOL "Should Utilib use BOOST?")
+
+
+Index: CMakeLists.txt
+===================================================================
+--- src/libs/CMakeLists.txt	2013/03/25 19:19:06	1970
++++ src/libs/CMakeLists.txt	2013/03/25 19:51:47	1971
+@@ -77,8 +77,9 @@
+   list(APPEND libs ${MPI_LIBRARY})
+ endif()
+ 
+-if(UTILIB_HAVE_EXPAT_H AND EXPAT_LIB)
+-  list(APPEND libs ${EXPAT_LIB})
++if(UTILIB_HAVE_EXPAT AND EXPAT_FOUND)
++  include_directories(${EXPAT_INCLUDE_DIRS})
++  list(APPEND libs ${EXPAT_LIBRARIES})
+ endif()
+ if(MSVC)
+   list(APPEND libs dbghelp)
Index: sm/trunk/externalpackages/dakota/dakota_njs_notes_macos64.txt
===================================================================
--- /issm/trunk/externalpackages/dakota/dakota_njs_notes_macos64.txt	(revision 15395)
+++ 	(revision )
@@ -1,5 +1,0 @@
-Matlab might try to use its local /Applications/MATLAB_R2011b.app/sys/os/maci64/ fortran libraries
-instead of the gfortran package libraries.  Matlab library is missing some symbols, so you might
-need to link to the actual gfortran library 
-sudo cp /Applications/MATLAB_R2011b.app/sys/os/maci64/libgfortran.3.dynlib /Applications/MATLAB_R2011b.app/sys/os/maci64/libgfortran.3.dynlib.matlab
-sudo ln -s /usr/local/gfortran/lib/gcc/x86_64-apple-darwin10/4.6.2/libgfortran.3.dylib libgfortran.3.dylib
Index: sm/trunk/externalpackages/dakota/install-4.2-linux64-astrid.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-4.2-linux64-astrid.sh	(revision 15395)
+++ 	(revision )
@@ -1,97 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf Dakota
-rm -rf src 
-rm -rf install 
-mkdir src install 
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_4_3.src.tar.gz' 'Dakota_4_3.src.tar.gz'
-
-#Untar 
-tar -zxvf  Dakota_4_3.src.tar.gz
-
-#Move Dakota to src directory
-mv Dakota/* src
-rm -rf Dakota
-
-#Apply patches
-patch src/src/ParallelLibrary.C configs/4.2/ParallelLibrary.C.patch
-patch src/src/ParallelLibrary.H configs/4.2/ParallelLibrary.H.patch
-patch src/src/NIDRProblemDescDB.C configs/4.2/NIDRProblemDescDB.C.patch
-patch src/src/NonDSampling.C configs/4.2/NonDSampling.C.patch
-patch src/src/NonDLocalReliability.C configs/4.2/NonDLocalReliability.C.patch
-patch src/src/NonDUnilevelRBDO.C configs/4.2/NonDUnilevelRBDO.C.patch    #  source not even used?
-#patch -R src/packages/Pecos/src/LHSDriver.cpp configs/4.2/LHSDriver.cpp.patch
-
-#Configure dakota
-cd src
-./configure \
-	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
-	--without-graphics  \
-	--with-pic \
-	--disable-mpi \
-	--with-blas=/usr/lib64/libblas.so.3.0.3 \
-	--with-lapack=/usr/lib64/liblapack.so.3.0.3
-cd ..
-
-#Before compiling, if running on 64 bits, we need to active fPIC compilation. Some packages 
-#do not register -fPIC in Dakota, which is a problem. Edit the faulty Makefiles and add the -fPIC 
-#flag to the compilation.
-cat ./src/methods/NCSUOpt/Makefile | sed 's/FFLAGS = -g -O2/FFLAGS = -g -O2 -fPIC/g' >  temp
-mv temp ./src/methods/NCSUOpt/Makefile
-
-cat ./src/methods/acro/packages/pebbl/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
-mv temp ./src/methods/acro/packages/pebbl/src/Makefile
-
-cat ./src/methods/hopspack/src-nappspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
-mv temp ./src/methods/hopspack/src-nappspack/Makefile
-
-cat ./src/methods/hopspack/src-cddlib/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
-mv temp  ./src/methods/hopspack/src-cddlib/Makefile 
-
-cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
-mv temp  ./src/methods/hopspack/src-shared/Makefile 
-
-cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
-mv temp  ./src/methods/hopspack/src-shared/Makefile 
-
-cat ./src/methods/hopspack/src-conveyor/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2 -fPIC/g' > temp
-mv temp  ./src/methods/hopspack/src-conveyor/Makefile 
-
-cat ./src/methods/hopspack/src-appspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
-mv temp ./src/methods/hopspack/src-appspack/Makefile 
-
-cat ./src/methods/acro/packages/colin/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
-mv temp ./src/methods/acro/packages/colin/src/Makefile
-
-cat ./src/methods/acro/packages/coliny/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
-mv temp ./src/methods/acro/packages/coliny/src/Makefile
-
-cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CFLAGS = -O2/CFLAGS = -O2 -fPIC/g' > temp
-mv temp  ./src/methods/acro/packages/tpl/3po/Makefile 
-
-cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CFLAGS = -O2 -fpermissive -fPIC/g' > temp
-mv temp  ./src/methods/acro/packages/tpl/3po/Makefile 
-
-cat ./src/packages/ampl/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
-mv temp  ./src/packages/ampl/Makefile 
-
-#Compile and install dakota
-cd src 
-if [ $# -eq 0 ];
-then
-	make
-	make install
-else
-	make -j $1
-	make -j $1 install
-fi
-cd ..
-
-#Weird behaviour of Dakota: libamplsolver.a and amplsolver.a are not the same thing!
-cd install/lib
-mv libamplsolver.a libamplsolver.a.bak
-ln -s ../../src/packages/ampl/amplsolver.a ./libamplsolver.a
Index: sm/trunk/externalpackages/dakota/install-5.2-linux64-astrid.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-5.2-linux64-astrid.sh	(revision 15395)
+++ 	(revision )
@@ -1,51 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf Dakota
-rm -rf src 
-rm -rf install 
-mkdir src install 
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_5_2.src.tar.gz' 'Dakota_5_2.src.tar.gz'
-
-#Untar 
-tar -zxvf Dakota_5_2.src.tar.gz
-
-#Move Dakota to src directory
-mv Dakota/* src
-rm -rf Dakota
-
-#Apply patches
-patch src/src/ParallelLibrary.C configs/5.2/ParallelLibrary.C.patch
-patch src/src/ParallelLibrary.H configs/5.2/ParallelLibrary.H.patch
-#patch src/src/NIDRProblemDescDB.C configs/5.2/NIDRProblemDescDB.C.patch    #  causes segfault in 5.2
-patch src/src/NonDSampling.C configs/5.2/NonDSampling.C.patch
-patch src/src/NonDLocalReliability.C configs/5.2/NonDLocalReliability.C.patch
-patch src/src/NonDUnilevelRBDO.C configs/5.2/NonDUnilevelRBDO.C.patch    #  source not even used?
-patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.2/pecos_global_defs.hpp.patch
-
-#Configure dakota
-cd src
-./configure \
-	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
-	--without-graphics  \
-	--with-pic \
-	--disable-mpi \
-	--with-plugin \
-	--with-blas=/usr/lib64/libblas.so.3.0.3 \
-	--with-lapack=/usr/lib64/liblapack.so.3.0.3
-cd ..
-
-#Compile and install dakota
-cd src 
-if [ $# -eq 0 ];
-then
-	make
-	make install
-else
-	make -j $1
-	make -j $1 install
-fi
-cd ..
Index: /issm/trunk/externalpackages/dakota/install-5.2-linux64-larsen.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-5.2-linux64-larsen.sh	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/install-5.2-linux64-larsen.sh	(revision 15396)
@@ -0,0 +1,49 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_5_2.src.tar.gz' 'Dakota_5_2.src.tar.gz'
+
+#Untar 
+tar -zxvf Dakota_5_2.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C configs/5.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/5.2/ParallelLibrary.H.patch
+patch src/src/NonDSampling.C configs/5.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/5.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/5.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.2/pecos_global_defs.hpp.patch
+patch src/packages/teuchos/src/Teuchos_ConfigDefs.hpp configs/5.2/Teuchos_ConfigDefs.hpp.patch
+
+#Configure dakota
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
+	--without-graphics  \
+	--with-pic \
+	--disable-mpi \
+	--with-plugin \
+	--with-blas="$ISSM_DIR/externalpackages/petsc/install/lib/libfblas.a" \
+	--with-lapack="$ISSM_DIR/externalpackages/petsc/install/lib/libflapack.a"
+
+#Compile and install dakota
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/trunk/externalpackages/dakota/install-5.2-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-5.2-macosx64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/install-5.2-macosx64.sh	(revision 15396)
@@ -0,0 +1,51 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_5_2.src.tar.gz' 'Dakota_5_2.src.tar.gz'
+
+#Untar 
+tar -zxvf Dakota_5_2.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C configs/5.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/5.2/ParallelLibrary.H.patch
+#patch src/src/NIDRProblemDescDB.C configs/5.2/NIDRProblemDescDB.C.patch    #  causes segfault in 5.2
+patch src/src/NonDSampling.C configs/5.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/5.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/5.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.2/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
+	--without-graphics  \
+	--with-pic \
+	--disable-mpi \
+	--with-plugin \
+	--with-blas="-L$ISSM_DIR/externalpackages/petsc/install/lib -lfblas " \
+	--with-lapack="-L$ISSM_DIR/externalpackages/petsc/install/lib -lflapack "
+cd ..
+
+#Compile and install dakota
+cd src 
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/trunk/externalpackages/dakota/install-5.2-pleiades-petsc3.3.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-5.2-pleiades-petsc3.3.sh	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/install-5.2-pleiades-petsc3.3.sh	(revision 15396)
@@ -0,0 +1,59 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src
+rm -rf install
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_5_2.src.tar.gz' 'Dakota_5_2.src.tar.gz'
+
+#Untar 
+tar -zxvf Dakota_5_2.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C configs/5.2/ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H configs/5.2/ParallelLibrary.H.patch
+#patch src/src/NIDRProblemDescDB.C configs/5.2/NIDRProblemDescDB.C.patch    #  causes segfault in 5.2
+patch src/src/NonDSampling.C configs/5.2/NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C configs/5.2/NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C configs/5.2/NonDUnilevelRBDO.C.patch    #  source not even used?
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.2/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd src
+./configure \
+--prefix="$ISSM_DIR/externalpackages/dakota/install/" \
+--without-graphics  \
+--with-pic \
+--disable-mpi \
+--with-plugin \
+--with-blas="-L/nasa/intel/mkl/10.0.011/lib/em64t/ -lmkl -lmkl_lapack -liomp5 -lpthread" \
+--with-lapack="-L/nasa/intel/mkl/10.0.011/lib/em64t/ -lmkl -lmkl_lapack -liomp5 -lpthread"
+
+#--with-blas=/nasa/intel/Compiler/2012.0.032/mkl/lib/intel64/libmkl_intel_lp64.a \
+#--with-lapack=/nasa/intel/Compiler/2012.0.032/mkl/lib/intel64/libmkl_intel_lp64.a 
+#--with-blas="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread" \
+#--with-lapack="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread"
+#--with-blas="-L/nasa/intel/Compiler/11.1/046/mkl/lib/em64t/ -lmkl_intel_lp64 -lmkl_lapack" \
+#--with-lapack="-L/nasa/intel/Compiler/11.1/046/mkl/lib/em64t/ -lmkl_intel_lp64 -lmkl_lapack"
+
+cd ..
+
+#Compile and install dakota
+cd src
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/trunk/externalpackages/dakota/install-5.3.1-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-5.3.1-linux64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/dakota/install-5.3.1-linux64.sh	(revision 15396)
@@ -0,0 +1,50 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf build 
+rm -rf install 
+mkdir src build install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/dakota-5.3.1-public-src.tar.gz' 'dakota-5.3.1-public-src.tar.gz'
+
+#Untar 
+tar -zxvf dakota-5.3.1-public-src.tar.gz
+
+#Move Dakota to src directory
+mv dakota-5.3.1.src/* src
+rm -rf dakota-5.3.1.src
+
+#Set up Dakota cmake variables and config
+export DAK_SRC=$ISSM_DIR/externalpackages/dakota/src
+export DAK_BUILD=$ISSM_DIR/externalpackages/dakota/build
+cp $DAK_SRC/cmake/BuildDakotaTemplate.cmake $DAK_SRC/cmake/BuildDakotaCustom.cmake
+patch $DAK_SRC/cmake/BuildDakotaCustom.cmake configs/5.3.1/BuildDakotaCustom.cmake.patch
+patch $DAK_SRC/cmake/DakotaDev.cmake configs/5.3.1/DakotaDev.cmake.patch
+
+#Apply patches
+patch src/src/ParallelLibrary.cpp configs/5.3.1/ParallelLibrary.cpp.patch
+patch src/src/ParallelLibrary.hpp configs/5.3.1/ParallelLibrary.hpp.patch
+patch src/src/NonDSampling.cpp configs/5.3.1/NonDSampling.cpp.patch
+patch src/src/NonDLocalReliability.cpp configs/5.3.1/NonDLocalReliability.cpp.patch
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.3.1/pecos_global_defs.hpp.patch
+
+#Configure dakota
+cd $DAK_BUILD
+cmake -C $DAK_SRC/cmake/BuildDakotaCustom.cmake -C $DAK_SRC/cmake/DakotaDev.cmake $DAK_SRC
+cd ..
+
+#Compile and install dakota
+cd $DAK_BUILD
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/trunk/externalpackages/doxygen/install.sh
===================================================================
--- /issm/trunk/externalpackages/doxygen/install.sh	(revision 15395)
+++ /issm/trunk/externalpackages/doxygen/install.sh	(revision 15396)
@@ -4,4 +4,5 @@
 #Some cleanup
 rm -rf install src
+mkdir install
 
 #Download latest version
@@ -9,5 +10,5 @@
 
 #Configure doxygen
-cd install && ./configure --prefix "$ISSM_DIR/externalpackages/doxygen/install"
+cd src && ./configure --prefix "$ISSM_DIR/externalpackages/doxygen/install"
 if [ $# -eq 0 ]; then
 	make
Index: /issm/trunk/externalpackages/export_fig/license.txt
===================================================================
--- /issm/trunk/externalpackages/export_fig/license.txt	(revision 15395)
+++ /issm/trunk/externalpackages/export_fig/license.txt	(revision 15396)
@@ -2,23 +2,23 @@
 All rights reserved.
 
-Redistribution and use in source and binary forms, with or without 
-modification, are permitted provided that the following conditions are 
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
 met:
 
-    * Redistributions of source code must retain the above copyright 
+    * Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
-    * Redistributions in binary form must reproduce the above copyright 
-      notice, this list of conditions and the following disclaimer in 
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in
       the documentation and/or other materials provided with the distribution
-      
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
-AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
-ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
-LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
-CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
-SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
-INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
-CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
-ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
Index: /issm/trunk/externalpackages/export_fig/print2eps.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/print2eps.m	(revision 15395)
+++ /issm/trunk/externalpackages/export_fig/print2eps.m	(revision 15396)
@@ -21,5 +21,5 @@
 %   options - Additional parameter strings to be passed to print.
 
-% Copyright (C) Oliver Woodford 2008-2012
+% Copyright (C) Oliver Woodford 2008-2013
 
 % The idea of editing the EPS file to change line styles comes from Jiro
@@ -48,4 +48,6 @@
 %           sizes we don't want, due to listeners. Thanks to Malcolm Hudson
 %           for reporting the issue.
+% 22/03/13: Extend font swapping to axes labels. Thanks to Rasmus Ischebeck
+%           for reporting the issue.
 
 function print2eps(name, fig, varargin)
@@ -61,5 +63,5 @@
 end
 % Find all the used fonts in the figure
-font_handles = findobj(fig, '-property', 'FontName');
+font_handles = findall(fig, '-property', 'FontName');
 fonts = get(font_handles, 'FontName');
 if ~iscell(fonts)
Index: /issm/trunk/externalpackages/export_fig/user_string.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/user_string.m	(revision 15395)
+++ /issm/trunk/externalpackages/export_fig/user_string.m	(revision 15396)
@@ -19,5 +19,5 @@
 %   saved - Boolean indicating whether the save was succesful
 
-% Copyright (C) Oliver Woodford 2011
+% Copyright (C) Oliver Woodford 2011-2013
 
 % This method of saving paths avoids changing .m files which might be in a
@@ -26,4 +26,7 @@
 % the version control system. Thank you to Jonas Dorn for suggesting this
 % approach.
+
+% 10/01/2013 - Access files in text, not binary mode, as latter can cause
+% errors. Thanks to Christian for pointing this out.
 
 function string = user_string(string_name, string)
@@ -58,5 +61,5 @@
     end
     % Write the file
-    fid = fopen(string_name, 'w');
+    fid = fopen(string_name, 'wt');
     if fid == -1
         string = false;
@@ -64,5 +67,5 @@
     end
     try
-        fwrite(fid, string, '*char');
+        fprintf(fid, '%s', string);
     catch
         fclose(fid);
@@ -74,10 +77,10 @@
 else
     % Get string
-    fid = fopen(string_name, 'r');
+    fid = fopen(string_name, 'rt');
     if fid == -1
         string = '';
         return
     end
-    string = fread(fid, '*char')';
+    string = fgetl(fid);
     fclose(fid);
 end
Index: /issm/trunk/externalpackages/ffmpeg/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/ffmpeg/install-macosx64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/ffmpeg/install-macosx64.sh	(revision 15396)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install ffmpeg-1.1.2
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ffmpeg-1.1.2.tar.gz' 'ffmpeg-1.1.2.tar.gz'
+
+#Untar 
+tar -zxvf  ffmpeg-1.1.2.tar.gz
+
+#Move ffmpeg into src directory
+mv ffmpeg-1.1.2/* src
+rm -rf ffmpeg-1.1.2
+
+#Configure ffmpeg
+cd src
+
+export CFLAGS=" -arch x86_64"
+
+./configure --prefix="$ISSM_DIR/externalpackages/ffmpeg/install" --disable-yasm
+
+#Compile ffmpeg
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: sm/trunk/externalpackages/gdal/configs/GDALmake.opt.patch.astrid
===================================================================
--- /issm/trunk/externalpackages/gdal/configs/GDALmake.opt.patch.astrid	(revision 15395)
+++ 	(revision )
@@ -1,8 +1,0 @@
-31c31
-< LIBS	=	$(SDE_LIB) -I/usr/include -lsqlite3 -L/usr/lib -lexpat -ljpeg -lz  -lm -lrt -ldl  $(KAK_LIBS) $(DWG_LIBS) $(CURL_LIB) \
----
-> LIBS	=	$(SDE_LIB) -I/usr/include -lsqlite3 -L/usr/lib64 -lexpat -ljpeg -lz  -lm -lrt -ldl  $(KAK_LIBS) $(DWG_LIBS) $(CURL_LIB) \
-225c225
-< CURL_LIB	=	-L/usr/kerberos/lib64 -lcurl -ldl -lgssapi_krb5 -lkrb5 -lk5crypto -lcom_err -lidn -lssl -lcrypto -lz  
----
-> CURL_LIB	=	-L/usr/lib64 -lcurl -ldl -lgssapi_krb5 -lkrb5 -lk5crypto -lcom_err -lidn -lssl -lcrypto -lz  
Index: /issm/trunk/externalpackages/gdal/install-1.10-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install-1.10-linux64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/gdal/install-1.10-linux64.sh	(revision 15396)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#WARNING: you need to have python installed in externalpackages
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf gdal-1.10.0
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.10.0.tar.gz' 'gdal-1.10.0.tar.gz'
+
+#Untar 
+tar -zxvf  gdal-1.10.0.tar.gz
+
+#Move gdal into src directory
+mv gdal-1.10.0/* src
+rm -rf gdal-1.10.0
+
+#Configure gdal
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
+	--with-python \
+	--with-netcdf=no \
+	--with-jasper=no \
+	--without-hdf5
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/gdal/install-1.10-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install-1.10-macosx64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/gdal/install-1.10-macosx64.sh	(revision 15396)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf gdal-1.10.0
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.10.0.tar.gz' 'gdal-1.10.0.tar.gz'
+
+#Untar 
+tar -zxvf  gdal-1.10.0.tar.gz
+
+#Move gdal into src directory
+mv gdal-1.10.0/* src
+rm -rf gdal-1.10.0
+
+#Configure gdal
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
+	--with-python \
+	--with-netcdf=no \
+	--with-libiconv-prefix="/usr/lib/" \
+	--without-hdf5
+#Note:
+# look for libiconv in /usr/lib/ because there seemed to be a conflict with port's library
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: sm/trunk/externalpackages/gdal/install-1.6-linux64-astrid.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install-1.6-linux64-astrid.sh	(revision 15395)
+++ 	(revision )
@@ -1,41 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf src
-rm -rf install
-rm -rf gdal-1.6.0
-mkdir src install
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.6.0.tar.gz' 'gdal-1.6.0.tar.gz'
-
-#Untar 
-tar -zxvf  gdal-1.6.0.tar.gz
-
-#Move gdal into src directory
-mv gdal-1.6.0/* src
-rm -rf gdal-1.6.0
-
-#Configure gdal
-cd src
-./configure \
-	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
-	--without-python \
-	--without-png \
-	--with-netcdf=no \
-	--with-jasper=no \
-	--without-ld-shared \
-	--with-unix-stdio-64=no \
-	--with-expat-lib=/usr/lib64/libexpat.so
-
-#Patch GDALmake.opt
-patch GDALmake.opt ../configs/GDALmake.opt.patch.astrid
-
-#Compile and install gdal
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: sm/trunk/externalpackages/gdal/install-1.9-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install-1.9-linux64.sh	(revision 15395)
+++ 	(revision )
@@ -1,37 +1,0 @@
-#!/bin/bash
-set -eu
-
-#WARNING: you need to have python installed in externalpackages
-
-#Some cleanup
-rm -rf src
-rm -rf install
-rm -rf gdal-1.9.2
-mkdir src install
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.9.2.tar.gz' 'gdal-1.9.2.tar.gz'
-
-#Untar 
-tar -zxvf  gdal-1.9.2.tar.gz
-
-#Move gdal into src directory
-mv gdal-1.9.2/* src
-rm -rf gdal-1.9.2
-
-#Configure gdal
-cd src
-./configure \
-	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
-	--with-python \
-	--with-netcdf=no \
-	--with-jasper=no \
-	--without-hdf5
-
-#Compile and install gdal
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: sm/trunk/externalpackages/gdal/install-1.9-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install-1.9-macosx64.sh	(revision 15395)
+++ 	(revision )
@@ -1,34 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf src
-rm -rf install
-rm -rf gdal-1.9.2
-mkdir src install
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.9.2.tar.gz' 'gdal-1.9.2.tar.gz'
-
-#Untar 
-tar -zxvf  gdal-1.9.2.tar.gz
-
-#Move gdal into src directory
-mv gdal-1.9.2/* src
-rm -rf gdal-1.9.2
-
-#Configure gdal
-cd src
-./configure \
-	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
-	--with-python \
-	--with-netcdf=no \
-	--without-hdf5
-
-#Compile and install gdal
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: /issm/trunk/externalpackages/gsl/install-android.sh
===================================================================
--- /issm/trunk/externalpackages/gsl/install-android.sh	(revision 15395)
+++ /issm/trunk/externalpackages/gsl/install-android.sh	(revision 15396)
@@ -25,8 +25,7 @@
     cd src
 
-    mv ./../Makefile.am.patch ./
-    patch Makefile.am < Makefile.am.patch
+    patch Makefile.am < ./../Makefile.am.patch
 
-    autoreconf -i
+    autoreconf -if
 
     ./configure \
Index: /issm/trunk/externalpackages/gsl/install-ios.sh
===================================================================
--- /issm/trunk/externalpackages/gsl/install-ios.sh	(revision 15396)
+++ /issm/trunk/externalpackages/gsl/install-ios.sh	(revision 15396)
@@ -0,0 +1,63 @@
+#!/bin/bash
+set -eu
+
+source $ANDROID_DIR/android_aux.sh
+export DEVROOT="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/"
+export SDKROOT="$DEVROOT/SDKs/iPhoneOS6.0.sdk/"
+export CC="$DEVROOT/usr/bin/gcc -arch armv7"
+export CFLAGS="-O -arch armv7 -isysroot $SDKROOT"
+export CXXFLAGS="-O -arch armv7 -isysroot $SDKROOT"
+export CPP=$DEVROOT/usr/bin/cpp
+export CXX=$DEVROOT/usr/bin/g++
+export AR=$DEVROOT/usr/bin/ar
+export AS=$DEVROOT/usr/bin/as
+export LIBTOOL=$DEVROOT/usr/bin/libtool
+export LDFLAGS="-lstdc++ -arch armv7 -isysroot $SDKROOT"
+export STRIP=$DEVROOT/usr/bin/strip
+export RANLIB=$DEVROOT/usr/bin/ranlib
+
+
+if [[ $step == "1" || $step == "0" ]]; then
+
+    #Some cleanup
+    rm -rf src install gsl-1.15
+    mkdir src install
+
+    #Download from ISSM server
+    $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.' 'gsl-1.15.tar.gz'
+
+    #Untar 
+    tar -zxvf  gsl-1.15.tar.gz
+
+    #Move gsl into src directory
+    mv gsl-1.15/* src
+    rm -rf gsl-1.15
+fi
+
+#Configure gsl
+if [[ $step == "2" || $step == "0" ]]; then
+    cd src
+
+    patch Makefile.am < ./../Makefile.am.patch
+
+    autoreconf -if
+
+    ./configure \
+		--build="i386-apple-darwin10.8.0" \
+		--host="arm-apple-darwin10" \
+	    --prefix="$ISSM_DIR/externalpackages/gsl/install"
+fi
+
+#Compile gsl
+if [[ $step == "3" || $step == "0" ]]; then
+	cd $ISSM_DIR/externalpackages/gsl/src
+
+    if [ $# -eq 0 ]; then
+	    make 
+    else
+	    make -j $j 
+    fi
+
+    make install
+fi
+
Index: /issm/trunk/externalpackages/gsl/install-walgreen.sh
===================================================================
--- /issm/trunk/externalpackages/gsl/install-walgreen.sh	(revision 15396)
+++ /issm/trunk/externalpackages/gsl/install-walgreen.sh	(revision 15396)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install gsl-1.15
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.15.tar.gz' 'gsl-1.15.tar.gz'
+
+#Untar 
+tar -zxvf  gsl-1.15.tar.gz
+
+#Move gsl into src directory
+mv gsl-1.15/* src
+rm -rf gsl-1.15
+
+#Configure gsl
+cd src
+
+export CC=icc
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gsl/install" 
+
+#Compile gsl
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/math77/install.sh
===================================================================
--- /issm/trunk/externalpackages/math77/install.sh	(revision 15396)
+++ /issm/trunk/externalpackages/math77/install.sh	(revision 15396)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install math77
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/math77.tar.gz' 'math77.tar.gz'
+
+#Untar 
+tar -zxvf  math77.tar.gz
+
+#Move math77 into src directory
+mv math77/* src
+rm -rf math77
+
+#Configure math77
+cd src
+
+#Compile math77
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/matlab/install.sh
===================================================================
--- /issm/trunk/externalpackages/matlab/install.sh	(revision 15395)
+++ /issm/trunk/externalpackages/matlab/install.sh	(revision 15396)
@@ -2,19 +2,34 @@
 set -eu
 
-#Erase symlink
-rm -rf install
+if [ ! -h install ];
+then
+	echo "  ****************************************************************"
+	echo "  *                                                              *"
+	echo "  * you need create a symbolic link from matlab's root directory *"
+	echo "  *                                                              *"
+	echo "  * First, you need to locate matlab's root directory            *"
+	echo "  * The easiest way to find it is to launch matlab and run the   *"
+	echo "  * following command: matlabroot                                *"
+	echo "  * Then, create a symbolic link using the command 'ln -s ' the  *"
+	echo "  * target directory should be named 'install'                   *"
+	echo "  *                                                              *"
+	echo "  * Examples:                                                    *"
+	echo "  *    ln -s /usr/local/matlab712/ install                       *"
+	echo "  *    ln -s /Applications/MATLAB_R2012a.app/ install            *"
+	echo "  *                                                              *"
+	echo "  * run ./install.sh again to check that the link is correct     *"
+	echo "  *                                                              *"
+	echo "  ****************************************************************"
+else
 
-#Select or create a new simlink
-#ln -s /usr/local/pkgs/matlab-7.6/ install
-#ln -s /discover/vis/mathworks/matlab_r2011b/ install
-#ln -s /usr/local/matlab704/ install
-#ln -s /usr/local/matlab711/ install
-ln -s /usr/local/matlab712/ install
-
-# Macintosh (OSX) simlink 
-#ln -s /Applications/MATLAB_R2008a/ install
-#ln -s /Applications/MATLAB_R2009a.app/ install
-#ln -s /Applications/MATLAB_R2010a.app/ install
-#ln -s /Applications/MATLAB_R2012a.app/ install
-#ln -s /Applications/MATLAB_R2011a.app/ install
-#ln -s /Applications/MATLAB*.app/ install
+	#Read link
+	DIR=$(readlink install)
+	if [ -d $DIR ]
+	then
+		echo "Symbolic link correctly set"
+	else
+		rm -rf install
+		echo "Incorrect symbolic link:"
+		echo "provided target ($DIR) does not exist or is not a directory"
+	fi
+fi
Index: /issm/trunk/externalpackages/mpich/install-2_1.4-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-2_1.4-linux64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/mpich/install-2_1.4-linux64.sh	(revision 15396)
@@ -0,0 +1,30 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.4.tar.gz' 'mpich2-1.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.4.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.4/* src
+rm -rf mpich2-1.4
+
+#Configure mpich2
+cd src
+export -n F90 
+export CFLAGS="$CFLAGS -fPIC"
+export FFLAGS="$FFLAGS -fPIC"
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Compile mpich2 (parallel make not supported)
+make
+make install 
Index: /issm/trunk/externalpackages/mpich/install-2_1.4-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-2_1.4-macosx32.sh	(revision 15396)
+++ /issm/trunk/externalpackages/mpich/install-2_1.4-macosx32.sh	(revision 15396)
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.4.tar.gz' 'mpich2-1.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.4.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.4/* src
+rm -rf mpich2-1.4
+
+#Configure mpich2
+cd src
+export FFLAGS=" -m32"
+export CFLAGS=" -m32"
+export CXXFLAGS=" -arch i386"
+export CPPFLAGS=" -arch i386"
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-f91=gfortran \
+	--enable-sharedlibs=osx-gcc \
+	--enable-shared \
+	--enable-fc
+
+#Compile mpich2 (parallel make not supported)
+make
+make install 
Index: /issm/trunk/externalpackages/mpich/install-2_1.4-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-2_1.4-macosx64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/mpich/install-2_1.4-macosx64.sh	(revision 15396)
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.4.tar.gz' 'mpich2-1.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.4.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.4/* src
+rm -rf mpich2-1.4
+
+#Configure mpich2
+cd src
+export FCFLAGS=" -m64"
+export FFLAGS=" -m64"
+export CFLAGS=" -arch x86_64"
+export CXXFLAGS=" -arch x86_64"
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-f91 \
+	--enable-sharedlibs=osx-gcc \
+	--enable-shared \
+	--enable-fc
+
+#Compile mpich2 (parallel make not supported)
+make
+make install 
Index: /issm/trunk/externalpackages/mpich/install-2_1.4.1-p1-win7.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-2_1.4.1-p1-win7.sh	(revision 15396)
+++ /issm/trunk/externalpackages/mpich/install-2_1.4.1-p1-win7.sh	(revision 15396)
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+#In order to install MPICH2 on your platform, go to www.mpich.org/downloads 
+#and download the following file (Windows x86_64 for the Windows distribution): 
+#mpich2-1.4.1p1-win-x86-64.msi. This file is also hosted on the ISSM website.
+
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.4.1p1-win-x86-64.msi' 'mpich2-1.4.1p1-win-x86-64.msi'
+
+#once installed, create a symbolic link between the MPICH2 directory 
+#and the install directory. For example: 
+#ln -s /cygdrive/c/Program\ Files/MPICH2 install
Index: /issm/trunk/externalpackages/mpich/install-2_1.5-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-2_1.5-linux64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/mpich/install-2_1.5-linux64.sh	(revision 15396)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich2-1.5
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.5.tar.gz' 'mpich2-1.5.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.5.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.5/* src
+rm -rf mpich2-1.5
+
+#Configure mpich2
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Compile mpich2 (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/mpich/install-2_1.5-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-2_1.5-macosx64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/mpich/install-2_1.5-macosx64.sh	(revision 15396)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich2-1.5
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.5.tar.gz' 'mpich2-1.5.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.5.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.5/* src
+rm -rf mpich2-1.5
+
+#Configure mpich2
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Compile mpich2 (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/mpich/install-2_1.5-walgreen.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-2_1.5-walgreen.sh	(revision 15396)
+++ /issm/trunk/externalpackages/mpich/install-2_1.5-walgreen.sh	(revision 15396)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich2-1.5
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.5.tar.gz' 'mpich2-1.5.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.5.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.5/* src
+rm -rf mpich2-1.5
+
+#Configure mpich2
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	--with-device=ch3:sock
+
+#Compile mpich2 (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/mpich/install-3.0-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-3.0-linux64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/mpich/install-3.0-linux64.sh	(revision 15396)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich-3.0.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich-3.0.4.tar.gz' 'mpich-3.0.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich-3.0.4.tar.gz
+
+#Move mpich into src directory
+mv mpich-3.0.4/* src
+rm -rf mpich-3.0.4
+
+#Configure mpich
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Compile mpich (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/mpich/install-3.0-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-3.0-macosx64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/mpich/install-3.0-macosx64.sh	(revision 15396)
@@ -0,0 +1,33 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich-3.0.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich-3.0.4.tar.gz' 'mpich-3.0.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich-3.0.4.tar.gz
+
+#Move mpich into src directory
+mv mpich-3.0.4/* src
+rm -rf mpich-3.0.4
+
+#Configure mpich
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared \
+	CC=llvm-gcc \
+	FC=gfortran \
+	F77=gfortran 
+
+#Compile mpich (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/mumps/README
===================================================================
--- /issm/trunk/externalpackages/mumps/README	(revision 15396)
+++ /issm/trunk/externalpackages/mumps/README	(revision 15396)
@@ -0,0 +1,1 @@
+MUMPS install package. Better rely on Petsc to install this, but feel free to try.
Index: /issm/trunk/externalpackages/mumps/configs/Makefile-macosx64.inc
===================================================================
--- /issm/trunk/externalpackages/mumps/configs/Makefile-macosx64.inc	(revision 15396)
+++ /issm/trunk/externalpackages/mumps/configs/Makefile-macosx64.inc	(revision 15396)
@@ -0,0 +1,32 @@
+LPORDDIR   = $(topdir)/PORD/lib/
+IPORD      = -I$(topdir)/PORD/include/
+LPORD      = -L$(LPORDDIR) -lpord
+IMETIS = -I$(ISSM_DIR)/externalpackages/petsc/install/include/
+LMETIS = -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -lparmetis
+ORDERINGSC = -Dpord -Dmetis -Dparmetis
+ORDERINGSF = -Dprod -Dmetis -Dparmetis
+LORDERINGS  = $(LMETIS) $(LPORD) $(LSCOTCH)
+IORDERINGSC = $(IMETIS) $(IPORD) $(ISCOTCH)
+IORDERINGSF = $(ISCOTCH)
+RM = /bin/rm -f
+CC = $(ISSM_DIR)/externalpackages/mpich2/install/bin/mpicc
+OPTC    =  -PIC  -Wwrite-strings -Wno-strict-aliasing -Wno-unknown-pragmas -O 
+OUTC = -o 
+FC = $(ISSM_DIR)/externalpackages/mpich2/install/bin/mpif90
+FL = $(ISSM_DIR)/externalpackages/mpich2/install/bin/mpif90
+OPTF    =  -fPIC  -Wno-unused-variable -Wno-unused-dummy-argument -O  
+OUTF = -o 
+CDEFS   = -DAdd_
+AR      = /usr/bin/ar cr 
+LIBEXT  = .a
+RANLIB  = /usr/bin/ranlib -c
+SCALAP  = -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -lscalapack -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -lblacs
+INCPAR  = -I$(ISSM_DIR)/externalpackages/mpich2/install/include -I$(ISSM_DIR)/externalpackages/mpich2/install/include
+LIBPAR  = $(SCALAP) 
+INCSEQ  = -I$(topdir)/libseq
+LIBSEQ  =  $(LAPACK) -L$(topdir)/libseq -lmpiseq
+LIBBLAS = -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -lflapack -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -L$(ISSM_DIR)/externalpackages/petsc/src/macosx-gnu/lib -lfblas -L$(ISSM_DIR)/externalpackages/mpich2/install/lib -L/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/x86_64 -L/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/x86_64 -L/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1 -L/usr/llvm-gcc-4.2/lib/gcc -L$(ISSM_DIR)/externalpackages/petsc/src -L$(ISSM_DIR)/externalpackages/hdf5/install/lib -L$(ISSM_DIR)/externalpackages/netcdf/install/lib -L/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1 -L/usr/llvm-gcc-4.2/lib -L/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2/lib -lmpichf90 -lgfortran -L/usr/local/gfortran/lib/gcc/x86_64-apple-darwin11/4.6.2 -L/usr/local/gfortran/lib -lgfortran -lgcc_ext.10.5 -lquadmath -lm -lm
+OPTL    = -O -I.
+INCS = $(INCPAR)
+LIBS = $(LIBPAR)
+LIBSEQNEEDED =
Index: /issm/trunk/externalpackages/mumps/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/mumps/install-macosx64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/mumps/install-macosx64.sh	(revision 15396)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mumps-4.10.0-p3
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mumps-4.10.0-p3.tar.gz' 'mumps-4.10.0-p3.tar.gz'
+
+#Untar 
+tar -zxvf  mumps-4.10.0-p3.tar.gz
+
+#Move mumps into src directory
+mv mumps-4.10.0-p3/* src
+rm -rf mumps-4.10.0-p3
+
+#configuration: 
+cp configs/Makefile-macosx64.inc src/Makefile.inc
+
+#Configure mumps
+cd src
+
+#Compile mumps
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/netcdf-cxx/install.sh
===================================================================
--- /issm/trunk/externalpackages/netcdf-cxx/install.sh	(revision 15396)
+++ /issm/trunk/externalpackages/netcdf-cxx/install.sh	(revision 15396)
@@ -0,0 +1,23 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install netcdf-cxx-4.2
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/netcdf-cxx-4.2.tar.gz' 'netcdf-cxx-4.2.tar.gz'
+
+#Untar 
+tar -zxvf netcdf-cxx-4.2.tar.gz
+
+#Move metis into install directory
+mv netcdf-cxx-4.2/* install
+rm -rf netcdf-cxx-4.2
+
+#Compile
+export CXXFLAGS="-I$ISSM_DIR/externalpackages/netcdf/install/include "
+cd install 
+./configure --prefix="$ISSM_DIR/externalpackages/netcdf-cxx/install" 
+make
+make install
Index: /issm/trunk/externalpackages/openssl/install.sh
===================================================================
--- /issm/trunk/externalpackages/openssl/install.sh	(revision 15395)
+++ /issm/trunk/externalpackages/openssl/install.sh	(revision 15396)
@@ -15,5 +15,5 @@
 #Configure openssl
 cd src
-./config --prefix="$ISSM_DIR/externalpackages/openssl/install"
+./config --prefix="$ISSM_DIR/externalpackages/openssl/install" shared
 if [ $# -eq 0 ]; then
 	make
Index: sm/trunk/externalpackages/petsc/install-2.3.2-altix64-castor.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-altix64-castor.sh	(revision 15395)
+++ 	(revision )
@@ -1,65 +1,0 @@
-#!/bin/bash
-set -eu
-#Step 1: unzip and install
-#Step 2: After Plapack implodes
-STEP=0
-
-if [ $STEP -eq 1 ]; then
-	#Some cleanup
-	rm -rf install petsc-2.3.2-p3 src
-	mkdir install src
-
-	#Download from ISSM server
-	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz'
-
-	#Untar and move petsc to install directory
-	tar -zxvf  petsc-2.3.2-p3.tar.gz
-	mv petsc-2.3.2-p3/* install/
-	rm -rf petsc-2.3.2-p3
-
-	#configure
-	cd install
-	./config/configure.py \
-		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-		--with-batch=1  \
-		--ISSM_ARCH=$ISSM_ARCH \
-		--PETSC_DIR=$PETSC_DIR   \
-		--with-debugging=no \
-		--with-shared=0 COPTFLAGS=-O3 FOPTFLAGS=-O3 \
-		--with-blas-lapack-dir=/opt/intel/mkl/9.1.023 \
-		--with-mpi-lib=/usr/lib/libmpi.so \
-		--with-mpi-include=/usr/include  \
-		--with-mpi-shared=0 \
-		--download-mumps=yes \
-		--download-scalapack=yes \
-		--download-blacs=yes  \
-		--download-plapack=yes \
-		--FFLAGS=-I/usr/include \
-		--with-cc=icc \
-		--with-fc=ifort
-
-	echo "== Fix Plapack compilation manually (http://issm.jpl.nasa.gov/installation/compilationtroubleshooting/petsc232/) =="
-	echo "== Then run STEP=2 =="
-fi
-if [ $STEP -eq 2 ]; then
-	cd install
-	./config/configure.py  \
-		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-		--with-batch=1  \
-		--ISSM_ARCH=$ISSM_ARCH \
-		--PETSC_DIR=$PETSC_DIR   \
-		--with-debugging=no \
-		--with-shared=0 COPTFLAGS=-O3 FOPTFLAGS=-O3 \
-		--with-blas-lapack-dir=/opt/intel/mkl/9.1.023 \
-		--with-mpi-lib=/usr/lib/libmpi.so \
-		--with-mpi-include=/usr/include  \
-		--with-mpi-shared=0 \
-		--download-mumps=yes \
-		--download-scalapack=yes \
-		--download-blacs=yes  \
-		--with-plapack-dir=$PETSC_DIR/externalpackages/PLAPACKR32-hg/$ISSM_ARCH \
-		--FFLAGS=-I/usr/include \
-		--with-cc=icc \
-		--with-fc=ifort
-	echo "== Follow PETSc's instructions"
-fi
Index: sm/trunk/externalpackages/petsc/install-2.3.2-cosmos.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-cosmos.sh	(revision 15395)
+++ 	(revision )
@@ -1,36 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install petsc-2.3.2-p3 src
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz'
-
-#Untar and move petsc to install directory
-tar -zxvf  petsc-2.3.2-p3.tar.gz
-mv petsc-2.3.2-p3/* install/
-rm -rf petsc-2.3.2-p3
-
-#configure
-cd install
-PETSC_DIR=$ISSM_DIR/externalpackages/petsc/install
-./config/configure.py  \
-	--prefix=$PETSC_DIR \
-	--with-batch=1  \
-	--ISSM_ARCH=$ISSM_ARCH \
-	--PETSC_DIR=$PETSC_DIR   \
-	--with-debugging=no COPTFLAGS=-O3 FOPTFLAGS=-O3 \
-	--with-blas-lapack-dir=/opt/intel/mkl/10.0.5.025/ \
-	--with-mpi-dir=/opt/mpich/gm/intel10.1/  \
-	--download-mumps=yes \
-	--download-scalapack=yes \
-	--download-blacs=yes  \
-	--download-plapack=yes \
-	--FFLAGS=-I/usr/include  \
-	--with-mpi-shared=0
-
-#Compile petsc and install it
-make
-make install
Index: sm/trunk/externalpackages/petsc/install-2.3.2-linux64-astrid.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-linux64-astrid.sh	(revision 15395)
+++ 	(revision )
@@ -1,39 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install petsc-2.3.2-p3 src
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz'
-
-#Untar and move petsc to install directory
-tar -zxvf  petsc-2.3.2-p3.tar.gz
-mv petsc-2.3.2-p3/* install/
-rm -rf petsc-2.3.2-p3
-
-#configure
-cd install
-./config/configure.py  \
-	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
-	--PETSC_ARCH=linux-gnu-amd64 \
-	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-fc=gfortran \
-	--with-debugging=1 \
-	--with-shared=0 \
-	--download-mumps=yes \
-	--download-scalapack=yes \
-	--download-blacs=yes \
-	--download-blas=yes \
-	--download-f-blas-lapack=yes \
-	--FFLAGS=-I$ISSM_DIR/externalpackages/mpich2/install/include \
-	--download-plapack=yes \
-	--COPTFLAGS="-march=opteron -O2" \
-	--FOPTFLAGS="-march=opteron -O2" \
-	--CXXOPTFLAGS="-march=opteron -O2" 
-
-#Compile petsc and install it
-make
-make install
Index: sm/trunk/externalpackages/petsc/install-2.3.2-macosx32-eric.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-macosx32-eric.sh	(revision 15395)
+++ 	(revision )
@@ -1,72 +1,0 @@
-#!/bin/bash
-set -eu
-#Step 1: unzip and install
-#Step 2: After MUMPS Crashes
-STEP=0
-
-if [ $STEP -eq 1 ]; then
-	#Some cleanup
-	rm -rf install petsc-2.3.2-p3 src
-	mkdir install src
-
-	#Download from ISSM server
-	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz'
-
-	#Untar and move petsc to install directory
-	tar -zxvf  petsc-2.3.2-p3.tar.gz
-	mv petsc-2.3.2-p3/* install/
-	rm -rf petsc-2.3.2-p3
-
-	#configure
-	cd install
-	./config/configure.py  \
-		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-		--with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
-		--PETSC_ARCH=macosx-gnu \
-		--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install" \
-		--with-fc=/usr/local/bin/gfortran \
-		--with-debugging=0 \
-		--with-shared=0 \
-		--download-mumps=yes \
-		--download-scalapack=yes \
-		--download-blacs=yes \
-		--download-blas=yes \
-		--download-f-blas-lapack=yes \
-		--FFLAGS="-I$ISSM_DIR/externalpackages/mpich2/install/include -L$ISSM_DIR/externalpackages/mpich2/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran  -fPIC -arch i386" \
-		--download-plapack=yes \
-		--CXXFLAGS=" -fPIC -arch i386" \
-		--CFLAGS=" -fPIC -arch i386" \
-		--with-pic \
-		--with-fc="gfortran -arch i386 " \
-		--LDFLAGS="-arch i386"
-	echo "== Fix MUMPS compilation manually (http://issm.jpl.nasa.gov/installation/compilationtroubleshooting/petsc232/) =="
-	echo "== Then run STEP=2 =="
-fi
-
-if [ $STEP -eq 2 ]; then
-	cd install
-	./config/configure.py  \
-		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-		--with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
-		--PETSC_ARCH=macosx-gnu \
-		--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install" \
-		--with-fc=/usr/local/bin/gfortran \
-		--with-debugging=0 \
-		--with-shared=0 \
-		--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/externalpackages/MUMPS_4.6.3  \
-		--download-scalapack=yes \
-		--download-blacs=yes \
-		--download-blas=yes \
-		--download-f-blas-lapack=yes \
-		--FFLAGS="-I$ISSM_DIR/externalpackages/mpich2/install/include -L$ISSM_DIR/externalpackages/mpich2/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran  -fPIC -arch i386" \
-		--download-plapack=yes \
-		--CXXFLAGS=" -fPIC -arch i386" \
-		--CFLAGS=" -fPIC -arch i386" \
-		--with-pic \
-		--with-fc="gfortran -arch i386 " \
-		--LDFLAGS="-arch i386"
-
-	#Compile petsc and install it
-	make
-	make install
-fi
Index: sm/trunk/externalpackages/petsc/install-2.3.2-macosx32-ogive.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-macosx32-ogive.sh	(revision 15395)
+++ 	(revision )
@@ -1,35 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install petsc-2.3.2-p3 src
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz'
-
-#Untar and move petsc to install directory
-tar -zxvf  petsc-2.3.2-p3.tar.gz
-mv petsc-2.3.2-p3/* install/
-rm -rf petsc-2.3.2-p3
-
-#configure
-cd install
-./config/configure.py  --prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
-	--PETSC_ARCH=macosx-gnu \
-	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-fc=/usr/local/bin/gfortran \
-	--with-debugging=0 \
-	--with-shared=0 \
-	--download-mumps=yes \
-	--download-scalapack=yes \
-	--download-blacs=yes \
-	--download-blas=yes \
-	--download-f-blas-lapack=yes \
-	--FFLAGS="-I$ISSM_DIR/externalpackages/mpich2/install/include -L$ISSM_DIR/externalpackages/mpich2/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran" \
-	--download-plapack=yes
-
-#Compile petsc and install it
-make
-make install
Index: sm/trunk/externalpackages/petsc/install-2.3.2-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-macosx64.sh	(revision 15395)
+++ 	(revision )
@@ -1,35 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install petsc-2.3.2-p3 src
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz'
-
-#Untar and move petsc to install directory
-tar -zxvf  petsc-2.3.2-p3.tar.gz
-mv petsc-2.3.2-p3/* src/
-rm -rf petsc-2.3.2-p3
-
-#configure
-cd src
-./config/configure.py \
-  --prefix="$ISSM_DIR/externalpackages/petsc/install" \
-  --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
-  --PETSC_ARCH=macosx-gnu \
-  --with-mpi-dir="$ISSM_DIR/externalpackages/mpich2/install" \
-  --with-debugging=0 \
-  --with-shared-libraries=0 \
-  --download-mumps=yes \
-  --download-scalapack=yes \
-  --download-blacs=yes \
-  --download-blas=yes \
-  --download-plapack=yes  \
-  --download-parmetis=yes \
-  --download-f-blas-lapack=yes 
-
-#Compile petsc and install it
-make
-make install
Index: sm/trunk/externalpackages/petsc/install-2.3.2-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-pleiades.sh	(revision 15395)
+++ 	(revision )
@@ -1,71 +1,0 @@
-#!/bin/bash
-set -eu
-#Step 1: unzip and install
-#Step 2: After Plapack implodes
-STEP=0
-
-if [ $STEP -eq 1 ]; then
-	#Some cleanup
-	rm -rf install petsc-2.3.2-p3 src
-	mkdir install src
-
-	#Download from ISSM server
-	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz'
-
-	#Untar and move petsc to install directory
-	tar -zxvf  petsc-2.3.2-p3.tar.gz
-	mv petsc-2.3.2-p3/* install/
-	rm -rf petsc-2.3.2-p3
-
-	#configure
-	cd install
-	./config/configure.py  \
-		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-		--with-batch=1  \
-		--PETSC_ARCH=$ISSM_ARCH \
-		--PETSC_DIR=$PETSC_DIR   \
-		--with-debugging=no \
-		--with-shared=0 \
-		--with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
-		--with-mpi-lib=/nasa/sgi/mpt/1.23.nas/lib64/libmpi.so \
-		--with-mpi-include=/nasa/sgi/mpt/1.23.nas/include  \
-		--with-mpi-shared=0 \
-		--download-mumps=yes \
-		--download-scalapack=yes \
-		--download-blacs=yes  \
-		--download-plapack=yes \
-		--FFLAGS=-I/usr/include \
-		--with-cc=icc \
-		--with-fc=ifort \
-		--COPTFLAGS=" -O3 -xS" \
-		--FOPTFLAGS=" -O3 -xS" \
-		--CXXOPTFLAGS=" -O3 -xS"
-
-	echo "== Fix Plapack compilation manually (http://issm.jpl.nasa.gov/installation/compilationtroubleshooting/petsc232/) =="
-	echo "== Then run STEP=2 =="
-fi
-if [ $STEP -eq 2 ]; then
-	cd install
-	./config/configure.py  \
-		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-		--with-batch=1  \
-		--PETSC_ARCH=$ISSM_ARCH \
-		--PETSC_DIR=$PETSC_DIR   \
-		--with-debugging=no \
-		--with-shared=0 \
-		--with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
-		--with-mpi-lib=/nasa/sgi/mpt/1.23.nas/lib64/libmpi.so \
-		--with-mpi-include=/nasa/sgi/mpt/1.23.nas/include  \
-		--with-mpi-shared=0 \
-		--download-mumps=yes \
-		--download-scalapack=yes \
-		--download-blacs=yes  \
-		--with-plapack-dir=$PETSC_DIR/externalpackages/PLAPACKR32-hg/$ISSM_ARCH \
-		--FFLAGS=-I/usr/include \
-		--with-cc=icc \
-		--with-fc=ifort \
-		--COPTFLAGS=" -O3 -xS" \
-		--FOPTFLAGS=" -O3 -xS" \
-		--CXXOPTFLAGS=" -O3 -xS"
-	echo "== Follow PETSc's instructions"
-fi
Index: sm/trunk/externalpackages/petsc/install-2.3.2-win32-eric.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-win32-eric.sh	(revision 15395)
+++ 	(revision )
@@ -1,29 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install petsc-2.3.2-p3 src
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz'
-
-#Untar and move petsc to install directory
-tar -zxvf  petsc-2.3.2-p3.tar.gz
-mv petsc-2.3.2-p3/* install/
-rm -rf petsc-2.3.2-p3
-
-#configure
-cd install
-./config/configure.py  \
-	--with-parallel-no \
-	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--PETSC_ARCH=cygwin-intel \
-	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-debugging=0 \
-	--with-mpi=0 \
-	--download-c-blas-lapack=1
-
-#Compile petsc and install it
-make
-make install
Index: sm/trunk/externalpackages/petsc/install-2.3.2-win7.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-win7.sh	(revision 15395)
+++ 	(revision )
@@ -1,29 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install petsc-2.3.2-p3 src
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz'
-
-#Untar and move petsc to install directory
-tar -zxvf  petsc-2.3.2-p3.tar.gz
-mv petsc-2.3.2-p3/* install/
-rm -rf petsc-2.3.2-p3
-
-#configure
-cd install
-./config/configure.py  \
-	--with-parallel-no \
-	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--PETSC_ARCH=cygwin-intel \
-	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-debugging=0 \
-	--with-mpi=0 \
-	--download-c-blas-lapack=1
-
-#Compile petsc and install it
-make
-make install
Index: sm/trunk/externalpackages/petsc/install-3.1-linux64-astrid.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-linux64-astrid.sh	(revision 15395)
+++ 	(revision )
@@ -1,40 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install petsc-3.1-p7 src
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
-
-#Untar and move petsc to install directory
-tar -zxvf  petsc-3.1-p7.tar.gz
-mv petsc-3.1-p7/* src/
-rm -rf petsc-3.1-p7
-
-#configure
-cd src
-./config/configure.py \
- --prefix="$ISSM_DIR/externalpackages/petsc/install" \
- --with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
- --PETSC_ARCH=linux-gnu-amd64 \
- --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
- --with-debugging=0 \
- --with-shared=0 \
- --download-mumps=yes \
- --download-scalapack=yes \
- --download-blacs=yes \
- --download-blas=yes \
- --download-f-blas-lapack=yes \
- --download-parmetis=yes \
- --FFLAGS=-I$ISSM_DIR/externalpackages/mpich2/install/include \
- --download-plapack=yes \
- --COPTFLAGS="-march=opteron -O2" \
- --FOPTFLAGS="-march=opteron -O2" \
- --CXXOPTFLAGS="-march=opteron -O2" \
- --with-pic=1
-
-#Compile petsc and install it
-make
-make install
Index: /issm/trunk/externalpackages/petsc/install-3.1-linux64-berg.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-linux64-berg.sh	(revision 15396)
+++ /issm/trunk/externalpackages/petsc/install-3.1-linux64-berg.sh	(revision 15396)
@@ -0,0 +1,45 @@
+#!/bin/bash
+
+#Get number of cpus on current platform
+NUMCPUS=$1;
+
+#version of petsc?
+#version='2.3.2-p3';
+version='3.1-p7'
+#version='3.2-p3'
+
+#Some cleanup
+rm -rf install petsc-$version src
+
+#Create src and install directories
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+#Untar 
+tar -zxvf  petsc-$version.tar.gz
+
+#Move petsc to install directory or src depending on the version
+if [[ $version != "2.3.2-p3" ]]
+then	
+	mv petsc-$version/* src/
+	rm -rf petsc-$version
+	cd src
+else
+	mv petsc-$version/* install/
+	rm -rf petsc-$version
+	cd install
+fi
+
+#configure
+../configure.sh
+
+#Compile petsc and install it
+if [ -z $NUMCPUS ];
+then
+	make
+else
+	make -j $NUMCPUS
+fi
+make install
Index: /issm/trunk/externalpackages/petsc/install-3.1-macosx32-mathieu.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-macosx32-mathieu.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-3.1-macosx32-mathieu.sh	(revision 15396)
@@ -20,5 +20,5 @@
  --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
  --PETSC_ARCH=macosx-gnu \
- --with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
+ --with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
  --with-debugging=0 \
  --with-shared=0 \
@@ -29,5 +29,5 @@
  --download-f-blas-lapack=yes \
  --download-plapack=yes \
- --FFLAGS="-I$ISSM_DIR/externalpackages/mpich2/install/include -arch i386" \
+ --FFLAGS="-I$ISSM_DIR/externalpackages/mpich/install/include -arch i386" \
  --COPTFLAGS="-march=opteron -O2 -arch i386" \
  --FOPTFLAGS="-march=opteron -O2 -arch i386" \
Index: /issm/trunk/externalpackages/petsc/install-3.1-macosx32-ogive.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-macosx32-ogive.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-3.1-macosx32-ogive.sh	(revision 15396)
@@ -19,5 +19,5 @@
 	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
 	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
-	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
+	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
 	--PETSC_ARCH=macosx-gnu \
 	--with-fc=/usr/local/bin/gfortran \
@@ -34,5 +34,5 @@
 	--FOPTFLAGS="-march=opteron -O2 " \
 	--CXXOPTFLAGS="-march=opteron -O2 " \
-	--FFLAGS="-I$ISSM_DIR/externalpackages/mpich2/install/include -L$ISSM_DIR/externalpackages/mpich2/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran " 
+	--FFLAGS="-I$ISSM_DIR/externalpackages/mpich/install/include -L$ISSM_DIR/externalpackages/mpich/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran " 
 
 #Compile petsc and install it
Index: /issm/trunk/externalpackages/petsc/install-3.1-ubuntu64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-ubuntu64.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-3.1-ubuntu64.sh	(revision 15396)
@@ -18,5 +18,5 @@
 ./config/configure.py \
  --prefix="$ISSM_DIR/externalpackages/petsc/install" \
- --with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
+ --with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
  --PETSC_ARCH=linux-gnu\
  --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
@@ -29,5 +29,5 @@
  --download-f-blas-lapack=yes \
  --download-parmetis=yes \
- --FFLAGS=-I$ISSM_DIR/externalpackages/mpich2/install/include \
+ --FFLAGS=-I$ISSM_DIR/externalpackages/mpich/install/include \
  --download-plapack=yes \
  --COPTFLAGS="-O2" \
Index: /issm/trunk/externalpackages/petsc/install-3.1-win7-parallel.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-win7-parallel.sh	(revision 15396)
+++ /issm/trunk/externalpackages/petsc/install-3.1-win7-parallel.sh	(revision 15396)
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.1-p7.tar.gz' 'petsc-3.1-p7.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.1-p7.tar.gz
+mv petsc-3.1-p7/* src/
+rm -rf petsc-3.1-p7
+
+cd src
+./config/configure.py  \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_ARCH=cygwin-intel \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--download-c-blas-lapack=yes \
+	--with-cc='win32fe cl' \
+	--with-fc=0 \
+	--with-cxx='win32fe cl' \
+	--with-clanguage=cxx  \
+	--with-mpi-include="/cygdrive/c/MPICH2/include" \
+	--with-mpi-lib="/cygdrive/c/MPICH2/lib/mpi.lib"
+
+
+#Compile petsc and install it
+make
+make install
+
+patch ../install/include/petscfix.h ../configs/3.1/win7/petscfix.h.patch
Index: /issm/trunk/externalpackages/petsc/install-3.1-win7.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-win7.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-3.1-win7.sh	(revision 15396)
@@ -33,5 +33,5 @@
 # --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
 # --PETSC_ARCH=macosx-gnu \
-# --with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
+# --with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
 # --with-debugging=0 \
 # --with-shared=0 \
@@ -42,5 +42,5 @@
 # --download-f-blas-lapack=yes \
 # --download-plapack=yes \
-# --FFLAGS="-I$ISSM_DIR/externalpackages/mpich2/install/include -arch i386" \
+# --FFLAGS="-I$ISSM_DIR/externalpackages/mpich/install/include -arch i386" \
 # --COPTFLAGS="-march=opteron -O2 -arch i386" \
 # --FOPTFLAGS="-march=opteron -O2 -arch i386" \
Index: /issm/trunk/externalpackages/petsc/install-3.2-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.2-linux64.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-3.2-linux64.sh	(revision 15396)
@@ -18,5 +18,5 @@
 ./config/configure.py \
 	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
 	--with-clanguage=C++ \
 	--PETSC_ARCH=linux-gnu-amd64 \
Index: /issm/trunk/externalpackages/petsc/install-3.2-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.2-macosx64.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-3.2-macosx64.sh	(revision 15396)
@@ -20,5 +20,5 @@
   --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
   --PETSC_ARCH="macosx-gnu" \
-  --with-mpi-dir="$ISSM_DIR/externalpackages/mpich2/install" \
+  --with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
   --with-debugging=0 \
   --with-shared-libraries=1 \
Index: /issm/trunk/externalpackages/petsc/install-3.2-ubuntu64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.2-ubuntu64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/petsc/install-3.2-ubuntu64.sh	(revision 15396)
@@ -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/mpich \
+	--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/externalpackages/petsc/install-3.3-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.3-linux64.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-3.3-linux64.sh	(revision 15396)
@@ -3,14 +3,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.3-p2 src
+rm -rf install petsc-3.3-p6 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p2.tar.gz' 'petsc-3.3-p2.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p6.tar.gz' 'petsc-3.3-p6.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.3-p2.tar.gz
-mv petsc-3.3-p2/* src/
-rm -rf petsc-3.3-p2
+tar -zxvf  petsc-3.3-p6.tar.gz
+mv petsc-3.3-p6/* src/
+rm -rf petsc-3.3-p6
 
 #configure
@@ -18,5 +18,5 @@
 ./config/configure.py \
 	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
+	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
 	--PETSC_ARCH=linux-gnu-amd64 \
 	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
Index: /issm/trunk/externalpackages/petsc/install-3.3-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.3-macosx64.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-3.3-macosx64.sh	(revision 15396)
@@ -3,14 +3,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.3-p2 src
+rm -rf install petsc-3.3-p6 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p2.tar.gz' 'petsc-3.3-p2.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p6.tar.gz' 'petsc-3.3-p6.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.3-p2.tar.gz
-mv petsc-3.3-p2/* src/
-rm -rf petsc-3.3-p2
+tar -zxvf  petsc-3.3-p6.tar.gz
+mv petsc-3.3-p6/* src/
+rm -rf petsc-3.3-p6
 
 #configure
@@ -18,5 +18,5 @@
 ./config/configure.py \
 	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich2/install \
+	--with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
 	--PETSC_ARCH="macosx-gnu" \
 	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
@@ -30,5 +30,6 @@
 	--download-plapack=yes \
 	--download-parmetis=yes \
-	--download-metis=yes 
+	--download-metis=yes \
+	--with-debugging=yes
 
 #Compile petsc and install it
Index: /issm/trunk/externalpackages/petsc/install-3.3-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.3-pleiades.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-3.3-pleiades.sh	(revision 15396)
@@ -2,14 +2,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.3-p2 src
+rm -rf install petsc-3.3-p6 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p2.tar.gz' 'petsc-3.3-p2.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p6.tar.gz' 'petsc-3.3-p6.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.3-p2.tar.gz
-mv petsc-3.3-p2/* src/
-rm -rf petsc-3.3-p2
+tar -zxvf  petsc-3.3-p6.tar.gz
+mv petsc-3.3-p6/* src/
+rm -rf petsc-3.3-p6
 
 #configure
@@ -17,19 +17,17 @@
 ./config/configure.py \
  --prefix="$ISSM_DIR/externalpackages/petsc/install" \
- --with-batch=1  \
  --PETSC_ARCH="$ISSM_ARCH" \
  --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
  --with-debugging=0 \
  --with-shared-libraries=1 \
  --known-mpi-shared-libraries=1 \
  --with-mpi=1 \
- --with-mpi-lib=/nasa/sgi/mpt/2.06a67/lib/libmpi.so \
- --with-mpi-include=/nasa/sgi/mpt/2.06a67/include  \
- --download-blas=yes \
- --download-f-blas-lapack=yes \
- --download-mumps=yes \
+ --with-mpi-lib="/nasa/sgi/mpt/2.06rp16/lib/libmpi.so" \
+ --with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+ --with-blas-lapack-dir="/nasa/intel/Compiler/2013.1.117/composer_xe_2013.1.117/mkl/lib/intel64" \
  --download-scalapack=yes \
  --download-blacs=yes \
- --download-plapack=no \
+ --download-mumps=yes \
  --download-metis=yes \
  --download-parmetis=yes \
@@ -37,6 +35,4 @@
  --download-euclid=yes \
  --download-hypre=yes \
- --with-cxx=icc \
- --with-fc=ifort \
  --COPTFLAGS="-lmpi -O3" \
  --FOPTFLAGS="-lmpi -O3" \
@@ -52,7 +48,6 @@
 
 . /usr/share/modules/init/bash 
-module load comp-intel/2012.0.032 
-module load mpi-sgi/mpt.2.06a67  
-module load math/intel_mkl_64_10.0.011
+module load comp-intel/2013.1.117
+module load mpi-sgi/mpt.2.06rp16
 
 export PATH="$PATH:." 
Index: /issm/trunk/externalpackages/petsc/install-3.3-walgreen.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.3-walgreen.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-3.3-walgreen.sh	(revision 15396)
@@ -1,15 +1,15 @@
 #!/bin/bash
 
-##Some cleanup
-#rm -rf install petsc-3.3-p2 src
-#mkdir install src
-#
-##Download from ISSM server
-#$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p2.tar.gz' 'petsc-3.3-p2.tar.gz'
-#
-##Untar and move petsc to install directory
-#tar -zxvf  petsc-3.3-p2.tar.gz
-#mv petsc-3.3-p2/* src/
-#rm -rf petsc-3.3-p2
+#Some cleanup
+rm -rf install petsc-3.3-p6 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p6.tar.gz' 'petsc-3.3-p6.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.3-p6.tar.gz
+mv petsc-3.3-p6/* src/
+rm -rf petsc-3.3-p6
 
 #configure
@@ -18,25 +18,19 @@
  --prefix="$ISSM_DIR/externalpackages/petsc/install" \
  --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-mpi-dir=$ISSM_DIR/externalpackages/mpich/install \
  --with-debugging=0 \
  --with-shared-libraries=1 \
  --with-blas-lapack-dir=/opt/intel/mkl/10.0.1.014/ \
- --known-mpi-shared-libraries=1 \
- --with-mpi=1 \
  --download-mumps=yes \
  --download-blacs=yes  \
  --download-blas=yes \
  --download-f-blas-lapack=yes \
+ --download-scalapack=yes \
  --download-parmetis=yes \
  --download-metis=yes \
- --download-trilinos=yes \
- --download-euclid=yes \
- --download-spai=yes \
  --download-superlu=yes \
- --download-hypre=yes \
- --download-prometheus=yes \
- --with-cc=/opt/mpich/ch-p4/bin/mpicc \
- --with-cxx=/opt/mpich/ch-p4/bin/mpicxx \
- --with-fc=/opt/mpich/ch-p4/bin/mpif90 \
- --COPTFLAGS="-I/opt/mpich/ch-p4/include/ -lmpich -O3" \
- --FOPTFLAGS="-I/opt/mpich/ch-p4/include/ -lmpich -O3" \
- --CXXOPTFLAGS="-I/opt/mpich/ch-p4/include/ -lmpich -O3" 
+ #--download-hypre=yes 
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk/externalpackages/petsc/install-3.4-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-linux64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/petsc/install-3.4-linux64.sh	(revision 15396)
@@ -0,0 +1,36 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.4.1 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'
+
+#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
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-parmetis=yes \
+	--download-metis=yes \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk/externalpackages/petsc/install-3.4-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-macosx64.sh	(revision 15396)
+++ /issm/trunk/externalpackages/petsc/install-3.4-macosx64.sh	(revision 15396)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.4.1 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'
+
+#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
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+	--PETSC_ARCH="macosx-gnu" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-metis=yes \
+	--download-parmetis=yes \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--with-debugging=yes
+
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk/externalpackages/petsc/install-3.4-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-pleiades.sh	(revision 15396)
+++ /issm/trunk/externalpackages/petsc/install-3.4-pleiades.sh	(revision 15396)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.4.1 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'
+
+#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
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-batch=1  \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib="/nasa/sgi/mpt/2.06rp16/lib/libmpi.so" \
+ --with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+ --with-blas-lapack-dir="/nasa/intel/Compiler/2013.1.117/composer_xe_2013.1.117/mkl/lib/intel64" \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-mumps=yes \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --COPTFLAGS="-lmpi -O3" \
+ --FOPTFLAGS="-lmpi -O3" \
+ --CXXOPTFLAGS="-lmpi -O3"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l select=1:ncpus=1:model=wes 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010
+#PBS -m e 
+
+. /usr/share/modules/init/bash 
+module load comp-intel/2013.1.117
+module load mpi-sgi/mpt.2.06rp16
+
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub -q devel script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/trunk/externalpackages/petsc/install-dev-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-dev-linux64.sh	(revision 15395)
+++ /issm/trunk/externalpackages/petsc/install-dev-linux64.sh	(revision 15396)
@@ -4,5 +4,4 @@
 
 if [ $STEP -eq 1 ]; then
-	# Adapted from petsc 3.2. 
 	# Used Mercurial to get code
 	rm -rf src
@@ -33,5 +32,5 @@
 	./config/configure.py \
 	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich2/install" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
 	--with-clanguage=C++ \
 	--PETSC_ARCH=linux-gnu-amd64 \
Index: /issm/trunk/externalpackages/proj.4/install.sh
===================================================================
--- /issm/trunk/externalpackages/proj.4/install.sh	(revision 15396)
+++ /issm/trunk/externalpackages/proj.4/install.sh	(revision 15396)
@@ -0,0 +1,15 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install
+
+#Download trunk
+svn checkout http://svn.osgeo.org/metacrs/proj/trunk/proj install
+
+#compile
+cd install
+./configure --prefix="$ISSM_DIR/externalpackages/proj.4/install"
+make 
+make install
+cd ..
Index: /issm/trunk/externalpackages/scotch/install.sh
===================================================================
--- /issm/trunk/externalpackages/scotch/install.sh	(revision 15395)
+++ /issm/trunk/externalpackages/scotch/install.sh	(revision 15396)
@@ -18,11 +18,11 @@
 tar -xvzf scotch_5.1.6.tar.gz
 
+# Apply patches (all at once, since many)
+# (written by diff -rc old_src new_src > scotch.patch)
+patch -p0 < scotch.patch
+
 # Move scotch to src directory
 mv scotch_5.1/* src
 rm -rf scotch_5.1
-
-# Apply patches (all at once, since many)
-# (written by diff -rc old_src new_src > scotch.patch)
-patch -p0 < scotch.patch
 
 # Build scotch
Index: /issm/trunk/externalpackages/scotch/scotch.patch
===================================================================
--- /issm/trunk/externalpackages/scotch/scotch.patch	(revision 15395)
+++ /issm/trunk/externalpackages/scotch/scotch.patch	(revision 15396)
@@ -1,8 +1,8 @@
-Only in new5: bin
-Only in new5: include
-Only in new5: lib
-diff -rc src/src/libscotch/arch.c new5/src/libscotch/arch.c
-*** src/src/libscotch/arch.c	2008-09-27 07:48:01.000000000 -0700
---- new5/src/libscotch/arch.c	2010-07-21 17:13:15.583257119 -0700
+Only in src: bin
+Only in src: include
+Only in src: lib
+diff -crB scotch_5.1/src/libscotch/arch.c src/src/libscotch/arch.c
+*** scotch_5.1/src/libscotch/arch.c	2008-09-27 07:48:01.000000000 -0700
+--- src/src/libscotch/arch.c	2013-05-06 14:14:11.000000000 -0700
 ***************
 *** 173,187 ****
@@ -68,7 +68,7 @@
         memset     (archptr, 0, sizeof (Arch));     /* Initialize architecture body */
         return     (1);
-diff -rc src/src/libscotch/arch_cmplt.c new5/src/libscotch/arch_cmplt.c
-*** src/src/libscotch/arch_cmplt.c	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_cmplt.c	2010-07-21 17:13:15.585257133 -0700
+diff -crB scotch_5.1/src/libscotch/arch_cmplt.c src/src/libscotch/arch_cmplt.c
+*** scotch_5.1/src/libscotch/arch_cmplt.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_cmplt.c	2013-05-06 14:14:11.000000000 -0700
 ***************
 *** 90,99 ****
@@ -120,7 +120,7 @@
       return     (1);
     }
-diff -rc src/src/libscotch/arch_cmplt.h new5/src/libscotch/arch_cmplt.h
-*** src/src/libscotch/arch_cmplt.h	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_cmplt.h	2010-07-21 17:13:15.588257154 -0700
+diff -crB scotch_5.1/src/libscotch/arch_cmplt.h src/src/libscotch/arch_cmplt.h
+*** scotch_5.1/src/libscotch/arch_cmplt.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_cmplt.h	2013-05-06 14:14:11.000000000 -0700
 ***************
 *** 87,93 ****
@@ -137,7 +137,7 @@
   #define archCmpltArchFree           NULL
   ArchDomNum                  archCmpltDomNum     (const ArchCmplt * const, const ArchCmpltDom * const);
-diff -rc src/src/libscotch/arch_cmpltw.c new5/src/libscotch/arch_cmpltw.c
-*** src/src/libscotch/arch_cmpltw.c	2008-08-27 14:22:22.000000000 -0700
---- new5/src/libscotch/arch_cmpltw.c	2010-07-21 17:13:15.590257168 -0700
+diff -crB scotch_5.1/src/libscotch/arch_cmpltw.c src/src/libscotch/arch_cmpltw.c
+*** scotch_5.1/src/libscotch/arch_cmpltw.c	2008-08-27 14:22:22.000000000 -0700
+--- src/src/libscotch/arch_cmpltw.c	2013-05-06 14:14:12.000000000 -0700
 ***************
 *** 200,211 ****
@@ -209,7 +209,7 @@
         return     (1);
       }
-diff -rc src/src/libscotch/arch_cmpltw.h new5/src/libscotch/arch_cmpltw.h
-*** src/src/libscotch/arch_cmpltw.h	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_cmpltw.h	2010-07-21 17:13:15.592257181 -0700
+diff -crB scotch_5.1/src/libscotch/arch_cmpltw.h src/src/libscotch/arch_cmpltw.h
+*** scotch_5.1/src/libscotch/arch_cmpltw.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_cmpltw.h	2013-05-06 14:14:12.000000000 -0700
 ***************
 *** 86,92 ****
@@ -226,7 +226,7 @@
   int                         archCmpltwArchFree  (ArchCmpltw * restrict const);
   ArchDomNum                  archCmpltwDomNum    (const ArchCmpltw * const, const ArchCmpltwDom * const);
-diff -rc src/src/libscotch/arch_deco.c new5/src/libscotch/arch_deco.c
-*** src/src/libscotch/arch_deco.c	2008-09-28 06:35:27.000000000 -0700
---- new5/src/libscotch/arch_deco.c	2010-07-21 17:13:15.595257202 -0700
+diff -crB scotch_5.1/src/libscotch/arch_deco.c src/src/libscotch/arch_deco.c
+*** scotch_5.1/src/libscotch/arch_deco.c	2008-09-28 06:35:27.000000000 -0700
+--- src/src/libscotch/arch_deco.c	2013-05-06 14:14:12.000000000 -0700
 ***************
 *** 211,217 ****
@@ -267,7 +267,7 @@
     if ((sizeof (ArchDeco)    > sizeof (ArchDummy)) ||
         (sizeof (ArchDecoDom) > sizeof (ArchDomDummy))) {
-diff -rc src/src/libscotch/arch_deco.h new5/src/libscotch/arch_deco.h
-*** src/src/libscotch/arch_deco.h	2008-09-27 07:49:46.000000000 -0700
---- new5/src/libscotch/arch_deco.h	2010-07-21 17:13:15.597257216 -0700
+diff -crB scotch_5.1/src/libscotch/arch_deco.h src/src/libscotch/arch_deco.h
+*** scotch_5.1/src/libscotch/arch_deco.h	2008-09-27 07:49:46.000000000 -0700
+--- src/src/libscotch/arch_deco.h	2013-05-06 14:14:13.000000000 -0700
 ***************
 *** 113,119 ****
@@ -284,7 +284,7 @@
   int                         archDecoArchFree    (ArchDeco * const);
   Anum                        archDecoArchSize    (ArchDeco * const, const Anum);
-diff -rc src/src/libscotch/arch.h new5/src/libscotch/arch.h
-*** src/src/libscotch/arch.h	2009-04-28 08:11:27.000000000 -0700
---- new5/src/libscotch/arch.h	2010-07-21 17:13:15.600257237 -0700
+diff -crB scotch_5.1/src/libscotch/arch.h src/src/libscotch/arch.h
+*** scotch_5.1/src/libscotch/arch.h	2009-04-28 08:11:27.000000000 -0700
+--- src/src/libscotch/arch.h	2013-05-06 14:14:13.000000000 -0700
 ***************
 *** 175,181 ****
@@ -301,7 +301,7 @@
   char *                      archName            (const Arch * const);
   const ArchClass *           archClass           (const char * const);
-diff -rc src/src/libscotch/arch_hcub.c new5/src/libscotch/arch_hcub.c
-*** src/src/libscotch/arch_hcub.c	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_hcub.c	2010-07-21 17:13:15.602257251 -0700
+diff -crB scotch_5.1/src/libscotch/arch_hcub.c src/src/libscotch/arch_hcub.c
+*** scotch_5.1/src/libscotch/arch_hcub.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_hcub.c	2013-05-06 14:14:13.000000000 -0700
 ***************
 *** 88,95 ****
@@ -310,5 +310,5 @@
   ArchHcub * restrict const   archptr,
 ! FILE * restrict const       stream)
-! {
+  {
   #ifdef SCOTCH_DEBUG_ARCH1
     if ((sizeof (ArchHcub)    > sizeof (ArchDummy)) ||
@@ -325,9 +325,9 @@
 ! #endif /* NOFILEIO */
 !                                    )
-! {
-! #ifdef NOFILEIO
-! //  printf("archHcubArchLoad - napar=%d,archpar=%p\n",napar,archpar);
-! #endif /* NOFILEIO */
-! 
+  {
++ #ifdef NOFILEIO
++ //  printf("archHcubArchLoad - napar=%d,archpar=%p\n",napar,archpar);
++ #endif /* NOFILEIO */
++ 
   #ifdef SCOTCH_DEBUG_ARCH1
     if ((sizeof (ArchHcub)    > sizeof (ArchDummy)) ||
@@ -349,7 +349,7 @@
       errorPrint ("archHcubArchLoad: bad input");
       return     (1);
-diff -rc src/src/libscotch/arch_hcub.h new5/src/libscotch/arch_hcub.h
-*** src/src/libscotch/arch_hcub.h	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_hcub.h	2010-07-21 17:13:15.604257265 -0700
+diff -crB scotch_5.1/src/libscotch/arch_hcub.h src/src/libscotch/arch_hcub.h
+*** scotch_5.1/src/libscotch/arch_hcub.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_hcub.h	2013-05-06 14:14:14.000000000 -0700
 ***************
 *** 85,91 ****
@@ -366,7 +366,7 @@
   #define archHcubArchFree            NULL
   ArchDomNum                  archHcubDomNum      (const ArchHcub * const, const ArchHcubDom * const);
-diff -rc src/src/libscotch/arch_mesh.c new5/src/libscotch/arch_mesh.c
-*** src/src/libscotch/arch_mesh.c	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_mesh.c	2010-07-21 17:13:15.607257286 -0700
+diff -crB scotch_5.1/src/libscotch/arch_mesh.c src/src/libscotch/arch_mesh.c
+*** scotch_5.1/src/libscotch/arch_mesh.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_mesh.c	2013-05-06 14:14:14.000000000 -0700
 ***************
 *** 96,103 ****
@@ -465,7 +465,7 @@
       return     (1);
     }
-diff -rc src/src/libscotch/arch_mesh.h new5/src/libscotch/arch_mesh.h
-*** src/src/libscotch/arch_mesh.h	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_mesh.h	2010-07-21 17:13:15.610257307 -0700
+diff -crB scotch_5.1/src/libscotch/arch_mesh.h src/src/libscotch/arch_mesh.h
+*** scotch_5.1/src/libscotch/arch_mesh.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_mesh.h	2013-05-06 14:14:14.000000000 -0700
 ***************
 *** 96,102 ****
@@ -496,7 +496,7 @@
   #define archMesh3ArchFree           NULL
   ArchDomNum                  archMesh3DomNum     (const ArchMesh3 * const, const ArchMesh3Dom * const);
-diff -rc src/src/libscotch/arch_tleaf.c new5/src/libscotch/arch_tleaf.c
-*** src/src/libscotch/arch_tleaf.c	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_tleaf.c	2010-07-21 17:13:15.612257320 -0700
+diff -crB scotch_5.1/src/libscotch/arch_tleaf.c src/src/libscotch/arch_tleaf.c
+*** scotch_5.1/src/libscotch/arch_tleaf.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_tleaf.c	2013-05-06 14:14:14.000000000 -0700
 ***************
 *** 92,99 ****
@@ -505,5 +505,5 @@
   ArchTleaf * restrict const  archptr,
 ! FILE * restrict const       stream)
-! {
+  {
   #ifdef SCOTCH_DEBUG_ARCH1
     if ((sizeof (ArchTleaf)    > sizeof (ArchDummy)) ||
@@ -520,9 +520,9 @@
 ! #endif /* NOFILEIO */
 !                                    )
-! {
-! #ifdef NOFILEIO
-! //  printf("archTleafArchLoad - napar=%d,archpar=%p\n",napar,archpar);
-! #endif /* NOFILEIO */
-! 
+  {
++ #ifdef NOFILEIO
++ //  printf("archTleafArchLoad - napar=%d,archpar=%p\n",napar,archpar);
++ #endif /* NOFILEIO */
++ 
   #ifdef SCOTCH_DEBUG_ARCH1
     if ((sizeof (ArchTleaf)    > sizeof (ArchDummy)) ||
@@ -554,7 +554,7 @@
       return     (1);
     }
-diff -rc src/src/libscotch/arch_tleaf.h new5/src/libscotch/arch_tleaf.h
-*** src/src/libscotch/arch_tleaf.h	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_tleaf.h	2010-07-21 17:13:15.615257341 -0700
+diff -crB scotch_5.1/src/libscotch/arch_tleaf.h src/src/libscotch/arch_tleaf.h
+*** scotch_5.1/src/libscotch/arch_tleaf.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_tleaf.h	2013-05-06 14:14:15.000000000 -0700
 ***************
 *** 89,95 ****
@@ -571,7 +571,7 @@
   #define archTleafArchFree           NULL
   ArchDomNum                  archTleafDomNum     (const ArchTleaf * const, const ArchTleafDom * const);
-diff -rc src/src/libscotch/arch_torus.c new5/src/libscotch/arch_torus.c
-*** src/src/libscotch/arch_torus.c	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_torus.c	2010-07-21 17:13:15.618257362 -0700
+diff -crB scotch_5.1/src/libscotch/arch_torus.c src/src/libscotch/arch_torus.c
+*** scotch_5.1/src/libscotch/arch_torus.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_torus.c	2013-05-06 14:14:15.000000000 -0700
 ***************
 *** 90,97 ****
@@ -670,7 +670,7 @@
       return     (1);
     }
-diff -rc src/src/libscotch/arch_torus.h new5/src/libscotch/arch_torus.h
-*** src/src/libscotch/arch_torus.h	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/arch_torus.h	2010-07-21 17:13:15.620257376 -0700
+diff -crB scotch_5.1/src/libscotch/arch_torus.h src/src/libscotch/arch_torus.h
+*** scotch_5.1/src/libscotch/arch_torus.h	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/arch_torus.h	2013-05-06 14:14:15.000000000 -0700
 ***************
 *** 96,102 ****
@@ -701,7 +701,7 @@
   #define archTorus3ArchFree          NULL
   ArchDomNum                  archTorus3DomNum    (const ArchTorus3 * const, const ArchTorus3Dom * const);
-diff -rc src/src/libscotch/common.c new5/src/libscotch/common.c
-*** src/src/libscotch/common.c	2008-05-22 06:44:41.000000000 -0700
---- new5/src/libscotch/common.c	2010-07-21 17:13:15.622257390 -0700
+diff -crB scotch_5.1/src/libscotch/common.c src/src/libscotch/common.c
+*** scotch_5.1/src/libscotch/common.c	2008-05-22 06:44:41.000000000 -0700
+--- src/src/libscotch/common.c	2013-05-06 14:14:15.000000000 -0700
 ***************
 *** 100,106 ****
@@ -720,7 +720,7 @@
 + #endif /* MATLAB */
   }
-diff -rc src/src/libscotch/common.h new5/src/libscotch/common.h
-*** src/src/libscotch/common.h	2009-02-06 14:20:55.000000000 -0800
---- new5/src/libscotch/common.h	2010-07-21 17:15:06.061025001 -0700
+diff -crB scotch_5.1/src/libscotch/common.h src/src/libscotch/common.h
+*** scotch_5.1/src/libscotch/common.h	2009-02-06 14:20:55.000000000 -0800
+--- src/src/libscotch/common.h	2013-05-09 11:49:35.317220518 -0700
 ***************
 *** 1,3 ****
@@ -752,4 +752,25 @@
   
 --- 109,114 ----
+***************
+*** 171,179 ****
+  /** The file structure. **/
+  
+  typedef struct File_ {
+!   char *                    name;                 /*+ File name    +*/
+    FILE *                    pntr;                 /*+ File pointer +*/
+!   char *                    mode;                 /*+ Opening mode +*/
+  } File;
+  
+  /*
+--- 172,180 ----
+  /** The file structure. **/
+  
+  typedef struct File_ {
+!   const char *              name;                 /*+ File name    +*/
+    FILE *                    pntr;                 /*+ File pointer +*/
+!   const char *              mode;                 /*+ Opening mode +*/
+  } File;
+  
+  /*
 ***************
 *** 190,216 ****
@@ -837,7 +858,7 @@
 + 
 + #endif //#ifndef _SCOTCH_COMMON_H_
-diff -rc src/src/libscotch/common_integer.c new5/src/libscotch/common_integer.c
-*** src/src/libscotch/common_integer.c	2009-01-21 01:32:32.000000000 -0800
---- new5/src/libscotch/common_integer.c	2010-07-21 17:13:15.628257432 -0700
+diff -crB scotch_5.1/src/libscotch/common_integer.c src/src/libscotch/common_integer.c
+*** scotch_5.1/src/libscotch/common_integer.c	2009-01-21 01:32:32.000000000 -0800
+--- src/src/libscotch/common_integer.c	2013-05-06 14:14:16.000000000 -0700
 ***************
 *** 191,196 ****
@@ -910,7 +931,7 @@
   
   /*********************/
-diff -rc src/src/libscotch/common_memory.c new5/src/libscotch/common_memory.c
-*** src/src/libscotch/common_memory.c	2009-01-03 02:16:11.000000000 -0800
---- new5/src/libscotch/common_memory.c	2010-07-21 17:13:15.630257445 -0700
+diff -crB scotch_5.1/src/libscotch/common_memory.c src/src/libscotch/common_memory.c
+*** scotch_5.1/src/libscotch/common_memory.c	2009-01-03 02:16:11.000000000 -0800
+--- src/src/libscotch/common_memory.c	2013-05-06 14:14:16.000000000 -0700
 ***************
 *** 87,93 ****
@@ -1018,7 +1039,7 @@
   }
   #endif /* COMMON_MEMORY_TRACE */
-diff -rc src/src/libscotch/dummysizes.c new5/src/libscotch/dummysizes.c
-*** src/src/libscotch/dummysizes.c	2009-05-09 16:08:02.000000000 -0700
---- new5/src/libscotch/dummysizes.c	2010-07-21 17:13:15.633257466 -0700
+diff -crB scotch_5.1/src/libscotch/dummysizes.c src/src/libscotch/dummysizes.c
+*** scotch_5.1/src/libscotch/dummysizes.c	2009-05-09 16:08:02.000000000 -0700
+--- src/src/libscotch/dummysizes.c	2013-05-06 14:14:16.000000000 -0700
 ***************
 *** 267,271 ****
@@ -1031,7 +1052,7 @@
 + #endif /* MATLAB */
   }
-diff -rc src/src/libscotch/graph.c new5/src/libscotch/graph.c
-*** src/src/libscotch/graph.c	2008-05-22 06:44:42.000000000 -0700
---- new5/src/libscotch/graph.c	2010-07-21 17:13:15.635257480 -0700
+diff -crB scotch_5.1/src/libscotch/graph.c src/src/libscotch/graph.c
+*** scotch_5.1/src/libscotch/graph.c	2008-05-22 06:44:42.000000000 -0700
+--- src/src/libscotch/graph.c	2013-05-06 14:14:17.000000000 -0700
 ***************
 *** 135,141 ****
@@ -1054,7 +1075,7 @@
       if ((grafptr->edlotax != NULL) &&
           ((grafptr->flagval & GRAPHEDGEGROUP) == 0))
-diff -rc src/src/libscotch/graph.h new5/src/libscotch/graph.h
-*** src/src/libscotch/graph.h	2008-06-01 02:49:11.000000000 -0700
---- new5/src/libscotch/graph.h	2010-07-21 17:13:15.637257494 -0700
+diff -crB scotch_5.1/src/libscotch/graph.h src/src/libscotch/graph.h
+*** scotch_5.1/src/libscotch/graph.h	2008-06-01 02:49:11.000000000 -0700
+--- src/src/libscotch/graph.h	2013-05-06 14:14:17.000000000 -0700
 ***************
 *** 159,165 ****
@@ -1071,7 +1092,7 @@
   int                         graphSave           (const Graph * const, FILE * const);
   Gnum                        graphBase           (Graph * const, const Gnum);
-diff -rc src/src/libscotch/graph_io.c new5/src/libscotch/graph_io.c
-*** src/src/libscotch/graph_io.c	2008-05-22 06:44:42.000000000 -0700
---- new5/src/libscotch/graph_io.c	2010-07-21 17:13:15.639257508 -0700
+diff -crB scotch_5.1/src/libscotch/graph_io.c src/src/libscotch/graph_io.c
+*** scotch_5.1/src/libscotch/graph_io.c	2008-05-22 06:44:42.000000000 -0700
+--- src/src/libscotch/graph_io.c	2013-05-06 14:14:17.000000000 -0700
 ***************
 *** 86,92 ****
@@ -1309,7 +1330,7 @@
     }
   
-diff -rc src/src/libscotch/graph_io_scot.c new5/src/libscotch/graph_io_scot.c
-*** src/src/libscotch/graph_io_scot.c	2008-05-22 06:44:42.000000000 -0700
---- new5/src/libscotch/graph_io_scot.c	2010-07-21 17:13:15.641257522 -0700
+diff -crB scotch_5.1/src/libscotch/graph_io_scot.c src/src/libscotch/graph_io_scot.c
+*** scotch_5.1/src/libscotch/graph_io_scot.c	2008-05-22 06:44:42.000000000 -0700
+--- src/src/libscotch/graph_io_scot.c	2013-05-06 14:14:17.000000000 -0700
 ***************
 *** 89,95 ****
@@ -1326,7 +1347,7 @@
     }
   
-diff -rc src/src/libscotch/library_arch.c new5/src/libscotch/library_arch.c
-*** src/src/libscotch/library_arch.c	2008-05-22 06:44:42.000000000 -0700
---- new5/src/libscotch/library_arch.c	2010-07-21 17:13:15.643257536 -0700
+diff -crB scotch_5.1/src/libscotch/library_arch.c src/src/libscotch/library_arch.c
+*** scotch_5.1/src/libscotch/library_arch.c	2008-05-22 06:44:42.000000000 -0700
+--- src/src/libscotch/library_arch.c	2013-05-06 14:14:17.000000000 -0700
 ***************
 *** 120,128 ****
@@ -1361,7 +1382,7 @@
   
   /*+ This routine saves the given opaque
-diff -rc src/src/libscotch/library_arch_f.c new5/src/libscotch/library_arch_f.c
-*** src/src/libscotch/library_arch_f.c	2008-05-22 06:44:42.000000000 -0700
---- new5/src/libscotch/library_arch_f.c	2010-07-21 17:13:15.645257550 -0700
+diff -crB scotch_5.1/src/libscotch/library_arch_f.c src/src/libscotch/library_arch_f.c
+*** scotch_5.1/src/libscotch/library_arch_f.c	2008-05-22 06:44:42.000000000 -0700
+--- src/src/libscotch/library_arch_f.c	2013-05-06 14:14:18.000000000 -0700
 ***************
 *** 121,127 ****
@@ -1378,7 +1399,7 @@
     fclose (stream);                                /* This closes filenum too */
   
-diff -rc src/src/libscotch/library_error_exit.c new5/src/libscotch/library_error_exit.c
-*** src/src/libscotch/library_error_exit.c	2009-01-20 00:36:33.000000000 -0800
---- new5/src/libscotch/library_error_exit.c	2010-07-21 17:13:15.648257570 -0700
+diff -crB scotch_5.1/src/libscotch/library_error_exit.c src/src/libscotch/library_error_exit.c
+*** scotch_5.1/src/libscotch/library_error_exit.c	2009-01-20 00:36:33.000000000 -0800
+--- src/src/libscotch/library_error_exit.c	2013-05-06 14:14:18.000000000 -0700
 ***************
 *** 114,119 ****
@@ -1453,7 +1474,7 @@
 + #endif /* MATLAB */
   }
-diff -rc src/src/libscotch/library_graph.c new5/src/libscotch/library_graph.c
-*** src/src/libscotch/library_graph.c	2008-05-22 07:28:12.000000000 -0700
---- new5/src/libscotch/library_graph.c	2010-07-21 17:13:15.650257584 -0700
+diff -crB scotch_5.1/src/libscotch/library_graph.c src/src/libscotch/library_graph.c
+*** scotch_5.1/src/libscotch/library_graph.c	2008-05-22 07:28:12.000000000 -0700
+--- src/src/libscotch/library_graph.c	2013-05-06 14:14:18.000000000 -0700
 ***************
 *** 137,143 ****
@@ -1498,7 +1519,7 @@
   
   /*+ This routine saves the contents of the given
-diff -rc src/src/libscotch/library_graph_f.c new5/src/libscotch/library_graph_f.c
-*** src/src/libscotch/library_graph_f.c	2008-05-22 06:44:43.000000000 -0700
---- new5/src/libscotch/library_graph_f.c	2010-07-21 17:13:15.652257598 -0700
+diff -crB scotch_5.1/src/libscotch/library_graph_f.c src/src/libscotch/library_graph_f.c
+*** scotch_5.1/src/libscotch/library_graph_f.c	2008-05-22 06:44:43.000000000 -0700
+--- src/src/libscotch/library_graph_f.c	2013-05-06 14:14:18.000000000 -0700
 ***************
 *** 136,142 ****
@@ -1515,7 +1536,7 @@
     fclose (stream);                                /* This closes filenum too */
   
-diff -rc src/src/libscotch/library_graph_map.c new5/src/libscotch/library_graph_map.c
-*** src/src/libscotch/library_graph_map.c	2008-09-28 04:04:05.000000000 -0700
---- new5/src/libscotch/library_graph_map.c	2010-07-21 17:13:15.654257612 -0700
+diff -crB scotch_5.1/src/libscotch/library_graph_map.c src/src/libscotch/library_graph_map.c
+*** scotch_5.1/src/libscotch/library_graph_map.c	2008-09-28 04:04:05.000000000 -0700
+--- src/src/libscotch/library_graph_map.c	2013-05-06 14:14:19.000000000 -0700
 ***************
 *** 182,192 ****
@@ -1540,7 +1561,7 @@
   
   /*+ This routine computes a mapping
-diff -rc src/src/libscotch/library_graph_map_f.c new5/src/libscotch/library_graph_map_f.c
-*** src/src/libscotch/library_graph_map_f.c	2008-06-28 03:44:26.000000000 -0700
---- new5/src/libscotch/library_graph_map_f.c	2010-07-21 17:13:15.656257626 -0700
+diff -crB scotch_5.1/src/libscotch/library_graph_map_f.c src/src/libscotch/library_graph_map_f.c
+*** scotch_5.1/src/libscotch/library_graph_map_f.c	2008-06-28 03:44:26.000000000 -0700
+--- src/src/libscotch/library_graph_map_f.c	2013-05-06 14:14:19.000000000 -0700
 ***************
 *** 183,189 ****
@@ -1557,7 +1578,7 @@
     fclose (stream);                                /* This closes filenum too */
   
-diff -rc src/src/libscotch/library.h new5/src/libscotch/library.h
-*** src/src/libscotch/library.h	2009-05-09 16:08:03.000000000 -0700
---- new5/src/libscotch/library.h	2010-07-21 17:13:15.660257654 -0700
+diff -crB scotch_5.1/src/libscotch/library.h src/src/libscotch/library.h
+*** scotch_5.1/src/libscotch/library.h	2009-05-09 16:08:03.000000000 -0700
+--- src/src/libscotch/library.h	2013-05-06 14:14:19.000000000 -0700
 ***************
 *** 1,3 ****
@@ -1618,7 +1639,7 @@
 + 
 + #endif //#ifndef _SCOTCH_H_
-diff -rc src/src/libscotch/Makefile new5/src/libscotch/Makefile
-*** src/src/libscotch/Makefile	2009-05-09 16:08:04.000000000 -0700
---- new5/src/libscotch/Makefile	2010-07-21 17:13:15.665257689 -0700
+diff -crB scotch_5.1/src/libscotch/Makefile src/src/libscotch/Makefile
+*** scotch_5.1/src/libscotch/Makefile	2009-05-09 16:08:04.000000000 -0700
+--- src/src/libscotch/Makefile	2013-05-06 14:14:19.000000000 -0700
 ***************
 *** 49,55 ****
@@ -2037,7 +2058,7 @@
 + 					$(AR) $(ARFLAGS) $(@) $(?)
 + 					-$(RANLIB) $(@)
-diff -rc src/src/libscotch/mapping.h new5/src/libscotch/mapping.h
-*** src/src/libscotch/mapping.h	2008-10-27 08:27:47.000000000 -0700
---- new5/src/libscotch/mapping.h	2010-07-21 17:13:15.667257702 -0700
+diff -crB scotch_5.1/src/libscotch/mapping.h src/src/libscotch/mapping.h
+*** scotch_5.1/src/libscotch/mapping.h	2008-10-27 08:27:47.000000000 -0700
+--- src/src/libscotch/mapping.h	2013-05-06 14:14:20.000000000 -0700
 ***************
 *** 106,112 ****
@@ -2054,7 +2075,7 @@
   
   #undef static
-diff -rc src/src/libscotch/mapping_io.c new5/src/libscotch/mapping_io.c
-*** src/src/libscotch/mapping_io.c	2008-05-22 06:44:43.000000000 -0700
---- new5/src/libscotch/mapping_io.c	2010-07-21 17:13:15.670257723 -0700
+diff -crB scotch_5.1/src/libscotch/mapping_io.c src/src/libscotch/mapping_io.c
+*** scotch_5.1/src/libscotch/mapping_io.c	2008-05-22 06:44:43.000000000 -0700
+--- src/src/libscotch/mapping_io.c	2013-05-06 14:14:20.000000000 -0700
 ***************
 *** 199,204 ****
@@ -2143,7 +2164,7 @@
     return (0);
   }
-diff -rc src/src/libscotch/mesh_io_scot.c new5/src/libscotch/mesh_io_scot.c
-*** src/src/libscotch/mesh_io_scot.c	2008-05-22 06:44:43.000000000 -0700
---- new5/src/libscotch/mesh_io_scot.c	2010-07-21 17:13:15.672257737 -0700
+diff -crB scotch_5.1/src/libscotch/mesh_io_scot.c src/src/libscotch/mesh_io_scot.c
+*** scotch_5.1/src/libscotch/mesh_io_scot.c	2008-05-22 06:44:43.000000000 -0700
+--- src/src/libscotch/mesh_io_scot.c	2013-05-06 14:14:20.000000000 -0700
 ***************
 *** 85,91 ****
@@ -2160,7 +2181,7 @@
     }
   
-diff -rc src/src/libscotch/module.h new5/src/libscotch/module.h
-*** src/src/libscotch/module.h	2009-04-26 23:07:14.000000000 -0700
---- new5/src/libscotch/module.h	2010-07-21 17:13:15.675257758 -0700
+diff -crB scotch_5.1/src/libscotch/module.h src/src/libscotch/module.h
+*** scotch_5.1/src/libscotch/module.h	2009-04-26 23:07:14.000000000 -0700
+--- src/src/libscotch/module.h	2013-05-06 14:14:20.000000000 -0700
 ***************
 *** 1,3 ****
@@ -2201,7 +2222,7 @@
 + 
 + #endif //#ifndef _SCOTCH_MODULE_H_
-diff -rc src/src/libscotch/parser_ll.l new5/src/libscotch/parser_ll.l
-*** src/src/libscotch/parser_ll.l	2008-05-22 06:44:43.000000000 -0700
---- new5/src/libscotch/parser_ll.l	2010-07-21 17:13:15.677257772 -0700
+diff -crB scotch_5.1/src/libscotch/parser_ll.l src/src/libscotch/parser_ll.l
+*** scotch_5.1/src/libscotch/parser_ll.l	2008-05-22 06:44:43.000000000 -0700
+--- src/src/libscotch/parser_ll.l	2013-05-06 14:14:21.000000000 -0700
 ***************
 *** 192,197 ****
@@ -2230,7 +2251,7 @@
     yyrestart (yyin);                               /* (Re-)initialize the parser */
   #endif /* FLEX_SCANNER */
-diff -rc src/src/libscotch/parser_yy.y new5/src/libscotch/parser_yy.y
-*** src/src/libscotch/parser_yy.y	2008-10-22 15:12:48.000000000 -0700
---- new5/src/libscotch/parser_yy.y	2010-07-21 17:13:15.679257786 -0700
+diff -crB scotch_5.1/src/libscotch/parser_yy.y src/src/libscotch/parser_yy.y
+*** scotch_5.1/src/libscotch/parser_yy.y	2008-10-22 15:12:48.000000000 -0700
+--- src/src/libscotch/parser_yy.y	2013-05-06 14:14:21.000000000 -0700
 ***************
 *** 774,779 ****
@@ -2243,7 +2264,7 @@
     if (stratParserParse2 () != 0) {                /* Parse the strategy string */
       if (parserstratcurr != NULL)
-diff -rc src/src/libscotch/vgraph_separate_vw.c new5/src/libscotch/vgraph_separate_vw.c
-*** src/src/libscotch/vgraph_separate_vw.c	2008-05-22 06:44:43.000000000 -0700
---- new5/src/libscotch/vgraph_separate_vw.c	2010-07-21 17:13:15.682257807 -0700
+diff -crB scotch_5.1/src/libscotch/vgraph_separate_vw.c src/src/libscotch/vgraph_separate_vw.c
+*** scotch_5.1/src/libscotch/vgraph_separate_vw.c	2008-05-22 06:44:43.000000000 -0700
+--- src/src/libscotch/vgraph_separate_vw.c	2013-05-06 14:14:21.000000000 -0700
 ***************
 *** 83,88 ****
@@ -2265,7 +2286,7 @@
     return (0);
   }
-diff -rc src/src/Makefile new5/src/Makefile
-*** src/src/Makefile	2008-09-15 05:50:51.000000000 -0700
---- new5/src/Makefile	2010-07-21 17:13:15.684257821 -0700
+diff -crB scotch_5.1/src/Makefile src/src/Makefile
+*** scotch_5.1/src/Makefile	2008-09-15 05:50:51.000000000 -0700
+--- src/src/Makefile	2013-05-06 14:14:21.000000000 -0700
 ***************
 *** 97,102 ****
@@ -2284,8 +2305,8 @@
   					-$(CP) -f ../bin/[agm]*$(EXE) $(bindir)
   					-$(CP) -f ../include/*scotch*.h $(includedir)
-Only in new5/src: Makefile.inc
-diff -rc src/src/scotch/gmap.h new5/src/scotch/gmap.h
-*** src/src/scotch/gmap.h	2008-06-18 11:05:17.000000000 -0700
---- new5/src/scotch/gmap.h	2010-07-21 17:13:15.686257834 -0700
+Only in src/src: Makefile.inc
+diff -crB scotch_5.1/src/scotch/gmap.h src/src/scotch/gmap.h
+*** scotch_5.1/src/scotch/gmap.h	2008-06-18 11:05:17.000000000 -0700
+--- src/src/scotch/gmap.h	2013-05-06 14:14:22.000000000 -0700
 ***************
 *** 1,3 ****
@@ -2304,9 +2325,9 @@
 + 
 + #endif //#ifndef _SCOTCH_GMAP_H_
-Only in new5/src/scotch: gmap_mex.c
-Only in new5/src/scotch: gmapx.c
-diff -rc src/src/scotch/Makefile new5/src/scotch/Makefile
-*** src/src/scotch/Makefile	2009-04-27 02:19:43.000000000 -0700
---- new5/src/scotch/Makefile	2010-07-21 17:13:15.689257855 -0700
+Only in src/src/scotch: gmap_mex.c
+Only in src/src/scotch: gmapx.c
+diff -crB scotch_5.1/src/scotch/Makefile src/src/scotch/Makefile
+*** scotch_5.1/src/scotch/Makefile	2009-04-27 02:19:43.000000000 -0700
+--- src/src/scotch/Makefile	2013-05-06 14:14:22.000000000 -0700
 ***************
 *** 49,59 ****
Index: /issm/trunk/externalpackages/tao/install-2.2.sh
===================================================================
--- /issm/trunk/externalpackages/tao/install-2.2.sh	(revision 15396)
+++ /issm/trunk/externalpackages/tao/install-2.2.sh	(revision 15396)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+#http://www.mcs.anl.gov/research/projects/tao/download/tao-2.2-pre1.tar.gz
+
+#compatible with PETSc 3.4
+
+#Some cleanup
+rm -rf install tao-2.2-pre1
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tao-2.2-pre1.tar.gz' 'tao-2.2-pre1.tar.gz'
+
+#Untar 
+tar -zxvf  tao-2.2-pre1.tar.gz
+
+#move into place
+mv tao-2.2-pre1/* install/
+rm -rf tao-2.2-pre1
+
+#compile
+cd install
+export TAO_DIR="$ISSM_DIR/externalpackages/tao/install/"
+make
Index: /issm/trunk/externalpackages/vim/addons/vim/plugin/file_line.vim
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/plugin/file_line.vim	(revision 15395)
+++ /issm/trunk/externalpackages/vim/addons/vim/plugin/file_line.vim	(revision 15396)
@@ -1,16 +1,51 @@
+" Avoid installing twice or when in unsupported Vim version.
+if exists('g:loaded_file_line') || (v:version < 700)
+	finish
+endif
+let g:loaded_file_line = 1
+
 function! s:gotoline()
 	let file = bufname("%")
-	let names =  matchlist( file, '\(.*\):\(\d\+\)')
 
-	if len(names) != 0 && filereadable(names[1])
+	" :e command calls BufRead even though the file is a new one.
+	" As a workarround Jonas Pfenniger<jonas@pfenniger.name> added an
+	" AutoCmd BufRead, this will test if this file actually exists before
+	" searching for a file and line to goto.
+	if (filereadable(file))
+		return
+	endif
+
+	" Accept file:line:column: or file:line:column and file:line also
+	let nocol = 0
+	let names =  matchlist( file, '\(.\{-1,}\):\%(\(\d\+\)\%(:\(\d*\):\?\)\?\)\?$')
+
+	if empty(names)
+		"no column provided maybe?
+		let names =  matchlist( file, '\(.*\):\(\d\+\)')
+		let nocol = 1
+		if empty(names)
+			return
+		endif
+	endif
+
+	let file_name =  names[1]
+	let line_num  =  names[2] == ''? '0' : names[2]
+	let  col_num  = (names[3] == '' && !nocol) ? '0' : names[3]
+
+	if filereadable(file_name)
 		let l:bufn = bufnr("%")
-		exec ":e " . names[1]
-		exec ":" . names[2]
-		exec ":bdelete " . l:bufn
-		if foldlevel(names[2]) > 0
-			exec ":foldopen!"
+		exec ":bwipeout " l:bufn
+
+		exec "keepalt edit " . file_name
+		exec ":" . line_num
+		exec "normal! " . col_num . '|'
+		if foldlevel(line_num) > 0
+			exec "normal! zv"
 		endif
+
+		exec "normal! zz"
 	endif
 endfunction
 
 autocmd! BufNewFile *:* nested call s:gotoline()
+autocmd! BufRead *:* nested call s:gotoline()
Index: /issm/trunk/externalpackages/vim/addons/vim/plugin/matchit.vim
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/plugin/matchit.vim	(revision 15396)
+++ /issm/trunk/externalpackages/vim/addons/vim/plugin/matchit.vim	(revision 15396)
@@ -0,0 +1,812 @@
+"  matchit.vim: (global plugin) Extended "%" matching
+"  Last Change: Fri Jan 25 10:00 AM 2008 EST
+"  Maintainer:  Benji Fisher PhD   <benji@member.AMS.org>
+"  Version:     1.13.2, for Vim 6.3+
+"  URL:		http://www.vim.org/script.php?script_id=39
+
+" Documentation:
+"  The documentation is in a separate file, matchit.txt .
+
+" Credits:
+"  Vim editor by Bram Moolenaar (Thanks, Bram!)
+"  Original script and design by Raul Segura Acevedo
+"  Support for comments by Douglas Potts
+"  Support for back references and other improvements by Benji Fisher
+"  Support for many languages by Johannes Zellner
+"  Suggestions for improvement, bug reports, and support for additional
+"  languages by Jordi-Albert Batalla, Neil Bird, Servatius Brandt, Mark
+"  Collett, Stephen Wall, Dany St-Amant, Yuheng Xie, and Johannes Zellner.
+
+" Debugging:
+"  If you'd like to try the built-in debugging commands...
+"   :MatchDebug      to activate debugging for the current buffer
+"  This saves the values of several key script variables as buffer-local
+"  variables.  See the MatchDebug() function, below, for details.
+
+" TODO:  I should think about multi-line patterns for b:match_words.
+"   This would require an option:  how many lines to scan (default 1).
+"   This would be useful for Python, maybe also for *ML.
+" TODO:  Maybe I should add a menu so that people will actually use some of
+"   the features that I have implemented.
+" TODO:  Eliminate the MultiMatch function.  Add yet another argument to
+"   Match_wrapper() instead.
+" TODO:  Allow :let b:match_words = '\(\(foo\)\(bar\)\):\3\2:end\1'
+" TODO:  Make backrefs safer by using '\V' (very no-magic).
+" TODO:  Add a level of indirection, so that custom % scripts can use my
+"   work but extend it.
+
+" allow user to prevent loading
+" and prevent duplicate loading
+if exists("loaded_matchit") || &cp
+  finish
+endif
+let loaded_matchit = 1
+let s:last_mps = ""
+let s:last_words = ":"
+
+let s:save_cpo = &cpo
+set cpo&vim
+
+nnoremap <silent> %  :<C-U>call <SID>Match_wrapper('',1,'n') <CR>
+nnoremap <silent> g% :<C-U>call <SID>Match_wrapper('',0,'n') <CR>
+vnoremap <silent> %  :<C-U>call <SID>Match_wrapper('',1,'v') <CR>m'gv``
+vnoremap <silent> g% :<C-U>call <SID>Match_wrapper('',0,'v') <CR>m'gv``
+onoremap <silent> %  v:<C-U>call <SID>Match_wrapper('',1,'o') <CR>
+onoremap <silent> g% v:<C-U>call <SID>Match_wrapper('',0,'o') <CR>
+
+" Analogues of [{ and ]} using matching patterns:
+nnoremap <silent> [% :<C-U>call <SID>MultiMatch("bW", "n") <CR>
+nnoremap <silent> ]% :<C-U>call <SID>MultiMatch("W",  "n") <CR>
+vmap [% <Esc>[%m'gv``
+vmap ]% <Esc>]%m'gv``
+" vnoremap <silent> [% :<C-U>call <SID>MultiMatch("bW", "v") <CR>m'gv``
+" vnoremap <silent> ]% :<C-U>call <SID>MultiMatch("W",  "v") <CR>m'gv``
+onoremap <silent> [% v:<C-U>call <SID>MultiMatch("bW", "o") <CR>
+onoremap <silent> ]% v:<C-U>call <SID>MultiMatch("W",  "o") <CR>
+
+" text object:
+vmap a% <Esc>[%v]%
+
+" Auto-complete mappings:  (not yet "ready for prime time")
+" TODO Read :help write-plugin for the "right" way to let the user
+" specify a key binding.
+"   let g:match_auto = '<C-]>'
+"   let g:match_autoCR = '<C-CR>'
+" if exists("g:match_auto")
+"   execute "inoremap " . g:match_auto . ' x<Esc>"=<SID>Autocomplete()<CR>Pls'
+" endif
+" if exists("g:match_autoCR")
+"   execute "inoremap " . g:match_autoCR . ' <CR><C-R>=<SID>Autocomplete()<CR>'
+" endif
+" if exists("g:match_gthhoh")
+"   execute "inoremap " . g:match_gthhoh . ' <C-O>:call <SID>Gthhoh()<CR>'
+" endif " gthhoh = "Get the heck out of here!"
+
+let s:notslash = '\\\@<!\%(\\\\\)*'
+
+function! s:Match_wrapper(word, forward, mode) range
+  " In s:CleanUp(), :execute "set" restore_options .
+  let restore_options = (&ic ? " " : " no") . "ignorecase"
+  if exists("b:match_ignorecase")
+    let &ignorecase = b:match_ignorecase
+  endif
+  let restore_options = " ve=" . &ve . restore_options
+  set ve=
+  " If this function was called from Visual mode, make sure that the cursor
+  " is at the correct end of the Visual range:
+  if a:mode == "v"
+    execute "normal! gv\<Esc>"
+  endif
+  " In s:CleanUp(), we may need to check whether the cursor moved forward.
+  let startline = line(".")
+  let startcol = col(".")
+  " Use default behavior if called with a count.
+  if v:count
+    exe "normal! " . v:count . "%"
+    return s:CleanUp(restore_options, a:mode, startline, startcol)
+  end
+
+  " First step:  if not already done, set the script variables
+  "   s:do_BR	flag for whether there are backrefs
+  "   s:pat	parsed version of b:match_words
+  "   s:all	regexp based on s:pat and the default groups
+  "
+  if !exists("b:match_words") || b:match_words == ""
+    let match_words = ""
+    " Allow b:match_words = "GetVimMatchWords()" .
+  elseif b:match_words =~ ":"
+    let match_words = b:match_words
+  else
+    execute "let match_words =" b:match_words
+  endif
+" Thanks to Preben "Peppe" Guldberg and Bram Moolenaar for this suggestion!
+  if (match_words != s:last_words) || (&mps != s:last_mps) ||
+    \ exists("b:match_debug")
+    let s:last_words = match_words
+    let s:last_mps = &mps
+    " The next several lines were here before
+    " BF started messing with this script.
+    " quote the special chars in 'matchpairs', replace [,:] with \| and then
+    " append the builtin pairs (/*, */, #if, #ifdef, #else, #elif, #endif)
+    " let default = substitute(escape(&mps, '[$^.*~\\/?]'), '[,:]\+',
+    "  \ '\\|', 'g').'\|\/\*\|\*\/\|#if\>\|#ifdef\>\|#else\>\|#elif\>\|#endif\>'
+    let default = escape(&mps, '[$^.*~\\/?]') . (strlen(&mps) ? "," : "") .
+      \ '\/\*:\*\/,#if\%(def\)\=:#else\>:#elif\>:#endif\>'
+    " s:all = pattern with all the keywords
+    let match_words = match_words . (strlen(match_words) ? "," : "") . default
+    if match_words !~ s:notslash . '\\\d'
+      let s:do_BR = 0
+      let s:pat = match_words
+    else
+      let s:do_BR = 1
+      let s:pat = s:ParseWords(match_words)
+    endif
+    let s:all = substitute(s:pat, s:notslash . '\zs[,:]\+', '\\|', 'g')
+    let s:all = '\%(' . s:all . '\)'
+    " let s:all = '\%(' . substitute(s:all, '\\\ze[,:]', '', 'g') . '\)'
+    if exists("b:match_debug")
+      let b:match_pat = s:pat
+    endif
+  endif
+
+  " Second step:  set the following local variables:
+  "     matchline = line on which the cursor started
+  "     curcol    = number of characters before match
+  "     prefix    = regexp for start of line to start of match
+  "     suffix    = regexp for end of match to end of line
+  " Require match to end on or after the cursor and prefer it to
+  " start on or before the cursor.
+  let matchline = getline(startline)
+  if a:word != ''
+    " word given
+    if a:word !~ s:all
+      echohl WarningMsg|echo 'Missing rule for word:"'.a:word.'"'|echohl NONE
+      return s:CleanUp(restore_options, a:mode, startline, startcol)
+    endif
+    let matchline = a:word
+    let curcol = 0
+    let prefix = '^\%('
+    let suffix = '\)$'
+  " Now the case when "word" is not given
+  else	" Find the match that ends on or after the cursor and set curcol.
+    let regexp = s:Wholematch(matchline, s:all, startcol-1)
+    let curcol = match(matchline, regexp)
+    " If there is no match, give up.
+    if curcol == -1
+      return s:CleanUp(restore_options, a:mode, startline, startcol)
+    endif
+    let endcol = matchend(matchline, regexp)
+    let suf = strlen(matchline) - endcol
+    let prefix = (curcol ? '^.*\%'  . (curcol + 1) . 'c\%(' : '^\%(')
+    let suffix = (suf ? '\)\%' . (endcol + 1) . 'c.*$'  : '\)$')
+  endif
+  if exists("b:match_debug")
+    let b:match_match = matchstr(matchline, regexp)
+    let b:match_col = curcol+1
+  endif
+
+  " Third step:  Find the group and single word that match, and the original
+  " (backref) versions of these.  Then, resolve the backrefs.
+  " Set the following local variable:
+  " group = colon-separated list of patterns, one of which matches
+  "       = ini:mid:fin or ini:fin
+  "
+  " Reconstruct the version with unresolved backrefs.
+  let patBR = substitute(match_words.',',
+    \ s:notslash.'\zs[,:]*,[,:]*', ',', 'g')
+  let patBR = substitute(patBR, s:notslash.'\zs:\{2,}', ':', 'g')
+  " Now, set group and groupBR to the matching group: 'if:endif' or
+  " 'while:endwhile' or whatever.  A bit of a kluge:  s:Choose() returns
+  " group . "," . groupBR, and we pick it apart.
+  let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, patBR)
+  let i = matchend(group, s:notslash . ",")
+  let groupBR = strpart(group, i)
+  let group = strpart(group, 0, i-1)
+  " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix
+  if s:do_BR " Do the hard part:  resolve those backrefs!
+    let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline)
+  endif
+  if exists("b:match_debug")
+    let b:match_wholeBR = groupBR
+    let i = matchend(groupBR, s:notslash . ":")
+    let b:match_iniBR = strpart(groupBR, 0, i-1)
+  endif
+
+  " Fourth step:  Set the arguments for searchpair().
+  let i = matchend(group, s:notslash . ":")
+  let j = matchend(group, '.*' . s:notslash . ":")
+  let ini = strpart(group, 0, i-1)
+  let mid = substitute(strpart(group, i,j-i-1), s:notslash.'\zs:', '\\|', 'g')
+  let fin = strpart(group, j)
+  "Un-escape the remaining , and : characters.
+  let ini = substitute(ini, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
+  let mid = substitute(mid, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
+  let fin = substitute(fin, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
+  " searchpair() requires that these patterns avoid \(\) groups.
+  let ini = substitute(ini, s:notslash . '\zs\\(', '\\%(', 'g')
+  let mid = substitute(mid, s:notslash . '\zs\\(', '\\%(', 'g')
+  let fin = substitute(fin, s:notslash . '\zs\\(', '\\%(', 'g')
+  " Set mid.  This is optimized for readability, not micro-efficiency!
+  if a:forward && matchline =~ prefix . fin . suffix
+    \ || !a:forward && matchline =~ prefix . ini . suffix
+    let mid = ""
+  endif
+  " Set flag.  This is optimized for readability, not micro-efficiency!
+  if a:forward && matchline =~ prefix . fin . suffix
+    \ || !a:forward && matchline !~ prefix . ini . suffix
+    let flag = "bW"
+  else
+    let flag = "W"
+  endif
+  " Set skip.
+  if exists("b:match_skip")
+    let skip = b:match_skip
+  elseif exists("b:match_comment") " backwards compatibility and testing!
+    let skip = "r:" . b:match_comment
+  else
+    let skip = 's:comment\|string'
+  endif
+  let skip = s:ParseSkip(skip)
+  if exists("b:match_debug")
+    let b:match_ini = ini
+    let b:match_tail = (strlen(mid) ? mid.'\|' : '') . fin
+  endif
+
+  " Fifth step:  actually start moving the cursor and call searchpair().
+  " Later, :execute restore_cursor to get to the original screen.
+  let restore_cursor = virtcol(".") . "|"
+  normal! g0
+  let restore_cursor = line(".") . "G" .  virtcol(".") . "|zs" . restore_cursor
+  normal! H
+  let restore_cursor = "normal!" . line(".") . "Gzt" . restore_cursor
+  execute restore_cursor
+  call cursor(0, curcol + 1)
+  " normal! 0
+  " if curcol
+  "   execute "normal!" . curcol . "l"
+  " endif
+  if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
+    let skip = "0"
+  else
+    execute "if " . skip . "| let skip = '0' | endif"
+  endif
+  let sp_return = searchpair(ini, mid, fin, flag, skip)
+  let final_position = "call cursor(" . line(".") . "," . col(".") . ")"
+  " Restore cursor position and original screen.
+  execute restore_cursor
+  normal! m'
+  if sp_return > 0
+    execute final_position
+  endif
+  return s:CleanUp(restore_options, a:mode, startline, startcol, mid.'\|'.fin)
+endfun
+
+" Restore options and do some special handling for Operator-pending mode.
+" The optional argument is the tail of the matching group.
+fun! s:CleanUp(options, mode, startline, startcol, ...)
+  execute "set" a:options
+  " Open folds, if appropriate.
+  if a:mode != "o"
+    if &foldopen =~ "percent"
+      normal! zv
+    endif
+    " In Operator-pending mode, we want to include the whole match
+    " (for example, d%).
+    " This is only a problem if we end up moving in the forward direction.
+  elseif (a:startline < line(".")) ||
+	\ (a:startline == line(".") && a:startcol < col("."))
+    if a:0
+      " Check whether the match is a single character.  If not, move to the
+      " end of the match.
+      let matchline = getline(".")
+      let currcol = col(".")
+      let regexp = s:Wholematch(matchline, a:1, currcol-1)
+      let endcol = matchend(matchline, regexp)
+      if endcol > currcol  " This is NOT off by one!
+	execute "normal!" . (endcol - currcol) . "l"
+      endif
+    endif " a:0
+  endif " a:mode != "o" && etc.
+  return 0
+endfun
+
+" Example (simplified HTML patterns):  if
+"   a:groupBR	= '<\(\k\+\)>:</\1>'
+"   a:prefix	= '^.\{3}\('
+"   a:group	= '<\(\k\+\)>:</\(\k\+\)>'
+"   a:suffix	= '\).\{2}$'
+"   a:matchline	=  "123<tag>12" or "123</tag>12"
+" then extract "tag" from a:matchline and return "<tag>:</tag>" .
+fun! s:InsertRefs(groupBR, prefix, group, suffix, matchline)
+  if a:matchline !~ a:prefix .
+    \ substitute(a:group, s:notslash . '\zs:', '\\|', 'g') . a:suffix
+    return a:group
+  endif
+  let i = matchend(a:groupBR, s:notslash . ':')
+  let ini = strpart(a:groupBR, 0, i-1)
+  let tailBR = strpart(a:groupBR, i)
+  let word = s:Choose(a:group, a:matchline, ":", "", a:prefix, a:suffix,
+    \ a:groupBR)
+  let i = matchend(word, s:notslash . ":")
+  let wordBR = strpart(word, i)
+  let word = strpart(word, 0, i-1)
+  " Now, a:matchline =~ a:prefix . word . a:suffix
+  if wordBR != ini
+    let table = s:Resolve(ini, wordBR, "table")
+  else
+    " let table = "----------"
+    let table = ""
+    let d = 0
+    while d < 10
+      if tailBR =~ s:notslash . '\\' . d
+	" let table[d] = d
+	let table = table . d
+      else
+	let table = table . "-"
+      endif
+      let d = d + 1
+    endwhile
+  endif
+  let d = 9
+  while d
+    if table[d] != "-"
+      let backref = substitute(a:matchline, a:prefix.word.a:suffix,
+	\ '\'.table[d], "")
+	" Are there any other characters that should be escaped?
+      let backref = escape(backref, '*,:')
+      execute s:Ref(ini, d, "start", "len")
+      let ini = strpart(ini, 0, start) . backref . strpart(ini, start+len)
+      let tailBR = substitute(tailBR, s:notslash . '\zs\\' . d,
+	\ escape(backref, '\\'), 'g')
+    endif
+    let d = d-1
+  endwhile
+  if exists("b:match_debug")
+    if s:do_BR
+      let b:match_table = table
+      let b:match_word = word
+    else
+      let b:match_table = ""
+      let b:match_word = ""
+    endif
+  endif
+  return ini . ":" . tailBR
+endfun
+
+" Input a comma-separated list of groups with backrefs, such as
+"   a:groups = '\(foo\):end\1,\(bar\):end\1'
+" and return a comma-separated list of groups with backrefs replaced:
+"   return '\(foo\):end\(foo\),\(bar\):end\(bar\)'
+fun! s:ParseWords(groups)
+  let groups = substitute(a:groups.",", s:notslash.'\zs[,:]*,[,:]*', ',', 'g')
+  let groups = substitute(groups, s:notslash . '\zs:\{2,}', ':', 'g')
+  let parsed = ""
+  while groups =~ '[^,:]'
+    let i = matchend(groups, s:notslash . ':')
+    let j = matchend(groups, s:notslash . ',')
+    let ini = strpart(groups, 0, i-1)
+    let tail = strpart(groups, i, j-i-1) . ":"
+    let groups = strpart(groups, j)
+    let parsed = parsed . ini
+    let i = matchend(tail, s:notslash . ':')
+    while i != -1
+      " In 'if:else:endif', ini='if' and word='else' and then word='endif'.
+      let word = strpart(tail, 0, i-1)
+      let tail = strpart(tail, i)
+      let i = matchend(tail, s:notslash . ':')
+      let parsed = parsed . ":" . s:Resolve(ini, word, "word")
+    endwhile " Now, tail has been used up.
+    let parsed = parsed . ","
+  endwhile " groups =~ '[^,:]'
+  let parsed = substitute(parsed, ',$', '', '')
+  return parsed
+endfun
+
+" TODO I think this can be simplified and/or made more efficient.
+" TODO What should I do if a:start is out of range?
+" Return a regexp that matches all of a:string, such that
+" matchstr(a:string, regexp) represents the match for a:pat that starts
+" as close to a:start as possible, before being preferred to after, and
+" ends after a:start .
+" Usage:
+" let regexp = s:Wholematch(getline("."), 'foo\|bar', col(".")-1)
+" let i      = match(getline("."), regexp)
+" let j      = matchend(getline("."), regexp)
+" let match  = matchstr(getline("."), regexp)
+fun! s:Wholematch(string, pat, start)
+  let group = '\%(' . a:pat . '\)'
+  let prefix = (a:start ? '\(^.*\%<' . (a:start + 2) . 'c\)\zs' : '^')
+  let len = strlen(a:string)
+  let suffix = (a:start+1 < len ? '\(\%>'.(a:start+1).'c.*$\)\@=' : '$')
+  if a:string !~ prefix . group . suffix
+    let prefix = ''
+  endif
+  return prefix . group . suffix
+endfun
+
+" No extra arguments:  s:Ref(string, d) will
+" find the d'th occurrence of '\(' and return it, along with everything up
+" to and including the matching '\)'.
+" One argument:  s:Ref(string, d, "start") returns the index of the start
+" of the d'th '\(' and any other argument returns the length of the group.
+" Two arguments:  s:Ref(string, d, "foo", "bar") returns a string to be
+" executed, having the effect of
+"   :let foo = s:Ref(string, d, "start")
+"   :let bar = s:Ref(string, d, "len")
+fun! s:Ref(string, d, ...)
+  let len = strlen(a:string)
+  if a:d == 0
+    let start = 0
+  else
+    let cnt = a:d
+    let match = a:string
+    while cnt
+      let cnt = cnt - 1
+      let index = matchend(match, s:notslash . '\\(')
+      if index == -1
+	return ""
+      endif
+      let match = strpart(match, index)
+    endwhile
+    let start = len - strlen(match)
+    if a:0 == 1 && a:1 == "start"
+      return start - 2
+    endif
+    let cnt = 1
+    while cnt
+      let index = matchend(match, s:notslash . '\\(\|\\)') - 1
+      if index == -2
+	return ""
+      endif
+      " Increment if an open, decrement if a ')':
+      let cnt = cnt + (match[index]=="(" ? 1 : -1)  " ')'
+      " let cnt = stridx('0(', match[index]) + cnt
+      let match = strpart(match, index+1)
+    endwhile
+    let start = start - 2
+    let len = len - start - strlen(match)
+  endif
+  if a:0 == 1
+    return len
+  elseif a:0 == 2
+    return "let " . a:1 . "=" . start . "| let " . a:2 . "=" . len
+  else
+    return strpart(a:string, start, len)
+  endif
+endfun
+
+" Count the number of disjoint copies of pattern in string.
+" If the pattern is a literal string and contains no '0' or '1' characters
+" then s:Count(string, pattern, '0', '1') should be faster than
+" s:Count(string, pattern).
+fun! s:Count(string, pattern, ...)
+  let pat = escape(a:pattern, '\\')
+  if a:0 > 1
+    let foo = substitute(a:string, '[^'.a:pattern.']', "a:1", "g")
+    let foo = substitute(a:string, pat, a:2, "g")
+    let foo = substitute(foo, '[^' . a:2 . ']', "", "g")
+    return strlen(foo)
+  endif
+  let result = 0
+  let foo = a:string
+  let index = matchend(foo, pat)
+  while index != -1
+    let result = result + 1
+    let foo = strpart(foo, index)
+    let index = matchend(foo, pat)
+  endwhile
+  return result
+endfun
+
+" s:Resolve('\(a\)\(b\)', '\(c\)\2\1\1\2') should return table.word, where
+" word = '\(c\)\(b\)\(a\)\3\2' and table = '-32-------'.  That is, the first
+" '\1' in target is replaced by '\(a\)' in word, table[1] = 3, and this
+" indicates that all other instances of '\1' in target are to be replaced
+" by '\3'.  The hard part is dealing with nesting...
+" Note that ":" is an illegal character for source and target,
+" unless it is preceded by "\".
+fun! s:Resolve(source, target, output)
+  let word = a:target
+  let i = matchend(word, s:notslash . '\\\d') - 1
+  let table = "----------"
+  while i != -2 " There are back references to be replaced.
+    let d = word[i]
+    let backref = s:Ref(a:source, d)
+    " The idea is to replace '\d' with backref.  Before we do this,
+    " replace any \(\) groups in backref with :1, :2, ... if they
+    " correspond to the first, second, ... group already inserted
+    " into backref.  Later, replace :1 with \1 and so on.  The group
+    " number w+b within backref corresponds to the group number
+    " s within a:source.
+    " w = number of '\(' in word before the current one
+    let w = s:Count(
+    \ substitute(strpart(word, 0, i-1), '\\\\', '', 'g'), '\(', '1')
+    let b = 1 " number of the current '\(' in backref
+    let s = d " number of the current '\(' in a:source
+    while b <= s:Count(substitute(backref, '\\\\', '', 'g'), '\(', '1')
+    \ && s < 10
+      if table[s] == "-"
+	if w + b < 10
+	  " let table[s] = w + b
+	  let table = strpart(table, 0, s) . (w+b) . strpart(table, s+1)
+	endif
+	let b = b + 1
+	let s = s + 1
+      else
+	execute s:Ref(backref, b, "start", "len")
+	let ref = strpart(backref, start, len)
+	let backref = strpart(backref, 0, start) . ":". table[s]
+	\ . strpart(backref, start+len)
+	let s = s + s:Count(substitute(ref, '\\\\', '', 'g'), '\(', '1')
+      endif
+    endwhile
+    let word = strpart(word, 0, i-1) . backref . strpart(word, i+1)
+    let i = matchend(word, s:notslash . '\\\d') - 1
+  endwhile
+  let word = substitute(word, s:notslash . '\zs:', '\\', 'g')
+  if a:output == "table"
+    return table
+  elseif a:output == "word"
+    return word
+  else
+    return table . word
+  endif
+endfun
+
+" Assume a:comma = ",".  Then the format for a:patterns and a:1 is
+"   a:patterns = "<pat1>,<pat2>,..."
+"   a:1 = "<alt1>,<alt2>,..."
+" If <patn> is the first pattern that matches a:string then return <patn>
+" if no optional arguments are given; return <patn>,<altn> if a:1 is given.
+fun! s:Choose(patterns, string, comma, branch, prefix, suffix, ...)
+  let tail = (a:patterns =~ a:comma."$" ? a:patterns : a:patterns . a:comma)
+  let i = matchend(tail, s:notslash . a:comma)
+  if a:0
+    let alttail = (a:1 =~ a:comma."$" ? a:1 : a:1 . a:comma)
+    let j = matchend(alttail, s:notslash . a:comma)
+  endif
+  let current = strpart(tail, 0, i-1)
+  if a:branch == ""
+    let currpat = current
+  else
+    let currpat = substitute(current, s:notslash . a:branch, '\\|', 'g')
+  endif
+  while a:string !~ a:prefix . currpat . a:suffix
+    let tail = strpart(tail, i)
+    let i = matchend(tail, s:notslash . a:comma)
+    if i == -1
+      return -1
+    endif
+    let current = strpart(tail, 0, i-1)
+    if a:branch == ""
+      let currpat = current
+    else
+      let currpat = substitute(current, s:notslash . a:branch, '\\|', 'g')
+    endif
+    if a:0
+      let alttail = strpart(alttail, j)
+      let j = matchend(alttail, s:notslash . a:comma)
+    endif
+  endwhile
+  if a:0
+    let current = current . a:comma . strpart(alttail, 0, j-1)
+  endif
+  return current
+endfun
+
+" Call this function to turn on debugging information.  Every time the main
+" script is run, buffer variables will be saved.  These can be used directly
+" or viewed using the menu items below.
+if !exists(":MatchDebug")
+  command! -nargs=0 MatchDebug call s:Match_debug()
+endif
+
+fun! s:Match_debug()
+  let b:match_debug = 1	" Save debugging information.
+  " pat = all of b:match_words with backrefs parsed
+  amenu &Matchit.&pat	:echo b:match_pat<CR>
+  " match = bit of text that is recognized as a match
+  amenu &Matchit.&match	:echo b:match_match<CR>
+  " curcol = cursor column of the start of the matching text
+  amenu &Matchit.&curcol	:echo b:match_col<CR>
+  " wholeBR = matching group, original version
+  amenu &Matchit.wh&oleBR	:echo b:match_wholeBR<CR>
+  " iniBR = 'if' piece, original version
+  amenu &Matchit.ini&BR	:echo b:match_iniBR<CR>
+  " ini = 'if' piece, with all backrefs resolved from match
+  amenu &Matchit.&ini	:echo b:match_ini<CR>
+  " tail = 'else\|endif' piece, with all backrefs resolved from match
+  amenu &Matchit.&tail	:echo b:match_tail<CR>
+  " fin = 'endif' piece, with all backrefs resolved from match
+  amenu &Matchit.&word	:echo b:match_word<CR>
+  " '\'.d in ini refers to the same thing as '\'.table[d] in word.
+  amenu &Matchit.t&able	:echo '0:' . b:match_table . ':9'<CR>
+endfun
+
+" Jump to the nearest unmatched "(" or "if" or "<tag>" if a:spflag == "bW"
+" or the nearest unmatched "</tag>" or "endif" or ")" if a:spflag == "W".
+" Return a "mark" for the original position, so that
+"   let m = MultiMatch("bW", "n") ... execute m
+" will return to the original position.  If there is a problem, do not
+" move the cursor and return "", unless a count is given, in which case
+" go up or down as many levels as possible and again return "".
+" TODO This relies on the same patterns as % matching.  It might be a good
+" idea to give it its own matching patterns.
+fun! s:MultiMatch(spflag, mode)
+  if !exists("b:match_words") || b:match_words == ""
+    return ""
+  end
+  let restore_options = (&ic ? "" : "no") . "ignorecase"
+  if exists("b:match_ignorecase")
+    let &ignorecase = b:match_ignorecase
+  endif
+  let startline = line(".")
+  let startcol = col(".")
+
+  " First step:  if not already done, set the script variables
+  "   s:do_BR	flag for whether there are backrefs
+  "   s:pat	parsed version of b:match_words
+  "   s:all	regexp based on s:pat and the default groups
+  " This part is copied and slightly modified from s:Match_wrapper().
+  let default = escape(&mps, '[$^.*~\\/?]') . (strlen(&mps) ? "," : "") .
+    \ '\/\*:\*\/,#if\%(def\)\=:#else\>:#elif\>:#endif\>'
+  " Allow b:match_words = "GetVimMatchWords()" .
+  if b:match_words =~ ":"
+    let match_words = b:match_words
+  else
+    execute "let match_words =" b:match_words
+  endif
+  if (match_words != s:last_words) || (&mps != s:last_mps) ||
+    \ exists("b:match_debug")
+    let s:last_words = match_words
+    let s:last_mps = &mps
+    if match_words !~ s:notslash . '\\\d'
+      let s:do_BR = 0
+      let s:pat = match_words
+    else
+      let s:do_BR = 1
+      let s:pat = s:ParseWords(match_words)
+    endif
+    let s:all = '\%(' . substitute(s:pat . (strlen(s:pat)?",":"") . default,
+      \	'[,:]\+','\\|','g') . '\)'
+    if exists("b:match_debug")
+      let b:match_pat = s:pat
+    endif
+  endif
+
+  " Second step:  figure out the patterns for searchpair()
+  " and save the screen, cursor position, and 'ignorecase'.
+  " - TODO:  A lot of this is copied from s:Match_wrapper().
+  " - maybe even more functionality should be split off
+  " - into separate functions!
+  let cdefault = (s:pat =~ '[^,]$' ? "," : "") . default
+  let open =  substitute(s:pat . cdefault,
+	\ s:notslash . '\zs:.\{-}' . s:notslash . ',', '\\),\\(', 'g')
+  let open =  '\(' . substitute(open, s:notslash . '\zs:.*$', '\\)', '')
+  let close = substitute(s:pat . cdefault,
+	\ s:notslash . '\zs,.\{-}' . s:notslash . ':', '\\),\\(', 'g')
+  let close = substitute(close, '^.\{-}' . s:notslash . ':', '\\(', '') . '\)'
+  if exists("b:match_skip")
+    let skip = b:match_skip
+  elseif exists("b:match_comment") " backwards compatibility and testing!
+    let skip = "r:" . b:match_comment
+  else
+    let skip = 's:comment\|string'
+  endif
+  let skip = s:ParseSkip(skip)
+  " let restore_cursor = line(".") . "G" . virtcol(".") . "|"
+  " normal! H
+  " let restore_cursor = "normal!" . line(".") . "Gzt" . restore_cursor
+  let restore_cursor = virtcol(".") . "|"
+  normal! g0
+  let restore_cursor = line(".") . "G" .  virtcol(".") . "|zs" . restore_cursor
+  normal! H
+  let restore_cursor = "normal!" . line(".") . "Gzt" . restore_cursor
+  execute restore_cursor
+
+  " Third step: call searchpair().
+  " Replace '\('--but not '\\('--with '\%(' and ',' with '\|'.
+  let openpat =  substitute(open, '\(\\\@<!\(\\\\\)*\)\@<=\\(', '\\%(', 'g')
+  let openpat = substitute(openpat, ',', '\\|', 'g')
+  let closepat = substitute(close, '\(\\\@<!\(\\\\\)*\)\@<=\\(', '\\%(', 'g')
+  let closepat = substitute(closepat, ',', '\\|', 'g')
+  if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
+    let skip = '0'
+  else
+    execute "if " . skip . "| let skip = '0' | endif"
+  endif
+  mark '
+  let level = v:count1
+  while level
+    if searchpair(openpat, '', closepat, a:spflag, skip) < 1
+      call s:CleanUp(restore_options, a:mode, startline, startcol)
+      return ""
+    endif
+    let level = level - 1
+  endwhile
+
+  " Restore options and return a string to restore the original position.
+  call s:CleanUp(restore_options, a:mode, startline, startcol)
+  return restore_cursor
+endfun
+
+" Search backwards for "if" or "while" or "<tag>" or ...
+" and return "endif" or "endwhile" or "</tag>" or ... .
+" For now, this uses b:match_words and the same script variables
+" as s:Match_wrapper() .  Later, it may get its own patterns,
+" either from a buffer variable or passed as arguments.
+" fun! s:Autocomplete()
+"   echo "autocomplete not yet implemented :-("
+"   if !exists("b:match_words") || b:match_words == ""
+"     return ""
+"   end
+"   let startpos = s:MultiMatch("bW")
+"
+"   if startpos == ""
+"     return ""
+"   endif
+"   " - TODO:  figure out whether 'if' or '<tag>' matched, and construct
+"   " - the appropriate closing.
+"   let matchline = getline(".")
+"   let curcol = col(".") - 1
+"   " - TODO:  Change the s:all argument if there is a new set of match pats.
+"   let regexp = s:Wholematch(matchline, s:all, curcol)
+"   let suf = strlen(matchline) - matchend(matchline, regexp)
+"   let prefix = (curcol ? '^.\{'  . curcol . '}\%(' : '^\%(')
+"   let suffix = (suf ? '\).\{' . suf . '}$'  : '\)$')
+"   " Reconstruct the version with unresolved backrefs.
+"   let patBR = substitute(b:match_words.',', '[,:]*,[,:]*', ',', 'g')
+"   let patBR = substitute(patBR, ':\{2,}', ':', "g")
+"   " Now, set group and groupBR to the matching group: 'if:endif' or
+"   " 'while:endwhile' or whatever.
+"   let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, patBR)
+"   let i = matchend(group, s:notslash . ",")
+"   let groupBR = strpart(group, i)
+"   let group = strpart(group, 0, i-1)
+"   " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix
+"   if s:do_BR
+"     let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline)
+"   endif
+" " let g:group = group
+"
+"   " - TODO:  Construct the closing from group.
+"   let fake = "end" . expand("<cword>")
+"   execute startpos
+"   return fake
+" endfun
+
+" Close all open structures.  "Get the heck out of here!"
+" fun! s:Gthhoh()
+"   let close = s:Autocomplete()
+"   while strlen(close)
+"     put=close
+"     let close = s:Autocomplete()
+"   endwhile
+" endfun
+
+" Parse special strings as typical skip arguments for searchpair():
+"   s:foo becomes (current syntax item) =~ foo
+"   S:foo becomes (current syntax item) !~ foo
+"   r:foo becomes (line before cursor) =~ foo
+"   R:foo becomes (line before cursor) !~ foo
+fun! s:ParseSkip(str)
+  let skip = a:str
+  if skip[1] == ":"
+    if skip[0] == "s"
+      let skip = "synIDattr(synID(line('.'),col('.'),1),'name') =~? '" .
+	\ strpart(skip,2) . "'"
+    elseif skip[0] == "S"
+      let skip = "synIDattr(synID(line('.'),col('.'),1),'name') !~? '" .
+	\ strpart(skip,2) . "'"
+    elseif skip[0] == "r"
+      let skip = "strpart(getline('.'),0,col('.'))=~'" . strpart(skip,2). "'"
+    elseif skip[0] == "R"
+      let skip = "strpart(getline('.'),0,col('.'))!~'" . strpart(skip,2). "'"
+    endif
+  endif
+  return skip
+endfun
+
+let &cpo = s:save_cpo
+
+" vim:sts=2:sw=2:
Index: /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 15395)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 15396)
@@ -6,14 +6,13 @@
 cat c.vim | sed "/ISSM's Enums begin/,/vim: ts=8/d" > temp
 echo "\"ISSM's Enums begin" >> temp
-cat ../../../../../src/c/EnumDefinitions/EnumDefinitions.h | grep -e "[0-9]Enum," -e "[a-z]Enum," -e "[A-Z]Enum," | grep -v StringToEnum | sed -e "s/,//g" | awk '{ printf "syn keyword cConstant " $1 "\n"}' >> temp
+cat ../../../../../src/c/shared/Enum/EnumDefinitions.h | grep -e "[0-9]Enum," -e "[a-z]Enum," -e "[A-Z]Enum," | grep -v StringToEnum | sed -e "s/,//g" | awk '{ printf "syn keyword cConstant " $1 "\n"}' >> temp
 echo "\"ISSM's Enums end" >> temp
 cat c.vim | sed "1,/ISSM's Enums end/d" >> temp
 mv temp c.vim
-exit 1
 
 #Synchronize objects
 cat c.vim | sed "/ISSM's objects begin/,/vim: ts=8/d" > temp
 echo "\"ISSM's objects begin" >> temp
-find ../../../../../src/c/classes -name "*.h" | sed -e "s/\// /g" -e "s/\.h//"| awk '{print  $(NF)}' | awk '{ printf "syn keyword cType " $1 "\n"}'>> 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
 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 15395)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 15396)
@@ -403,166 +403,89 @@
 "   please try to keep the alphabetical ordering                                                                    "
 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
-"ISSM containers:
-syn keyword	cType		Constraints DataSet Elements Inputs Loads Materials Nodes Parameters Results Vertices Options
 "Petsc
 syn keyword	cType		Vec Mat SeqVec SeqMat
 "other ISSM's syntax
-syn keyword	cType		mxArray ErrorException QuadtreeBox IssmDouble IssmPDouble Observations
+syn keyword	cType		mxArray ErrorException QuadtreeBox
+syn keyword	cType		IssmDouble IssmPDouble
 
 "ISSM's objects begin
-syn keyword cType GaussPenta
-syn keyword cType gaussobjects
-syn keyword cType GaussTria
-syn keyword cType objects
-syn keyword cType Material
+syn keyword cType Matdamageice
+syn keyword cType Materials
 syn keyword cType Matice
 syn keyword cType Matpar
-syn keyword cType objects
-syn keyword cType Contour
-syn keyword cType DoubleInput
-syn keyword cType Input
+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 Observations
+syn keyword cType GaussianVariogram
+syn keyword cType SphericalVariogram
+syn keyword cType Observation
+syn keyword cType RiftStruct
+syn keyword cType OptionUtilities
+syn keyword cType Options
+syn keyword cType Penpair
+syn keyword cType Loads
+syn keyword cType Icefront
+syn keyword cType Friction
+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 TriaP1Input
+syn keyword cType Inputs
 syn keyword cType TransientInput
 syn keyword cType PentaP1Input
-syn keyword cType KML_Icon
-syn keyword cType KML_Point
-syn keyword cType KML_LinearRing
-syn keyword cType KML_Feature
-syn keyword cType KMLFileReadUtils
-syn keyword cType KML_StyleSelector
-syn keyword cType KML_LatLonBox
-syn keyword cType KML_Attribute
-syn keyword cType KML_PolyStyle
-syn keyword cType KML_Object
-syn keyword cType KML_SubStyle
-syn keyword cType KML_LineString
-syn keyword cType KML_Overlay
-syn keyword cType KML_Container
-syn keyword cType KML_Polygon
-syn keyword cType KML_Geometry
-syn keyword cType KML_ColorStyle
-syn keyword cType KML_Placemark
-syn keyword cType KML_Unknown
-syn keyword cType KML_GroundOverlay
-syn keyword cType KML_Style
-syn keyword cType KML_Comment
-syn keyword cType KML_MultiGeometry
-syn keyword cType KML_LineStyle
-syn keyword cType KML_Folder
-syn keyword cType KML_Document
-syn keyword cType KML_File
-syn keyword cType DoubleVecParam
-syn keyword cType DoubleParam
-syn keyword cType DoubleMatArrayParam
-syn keyword cType DoubleMatParam
-syn keyword cType Param
-syn keyword cType FileParam
-syn keyword cType IntVecParam
-syn keyword cType IntParam
-syn keyword cType BoolParam
-syn keyword cType IntMatParam
-syn keyword cType VectorParam
-syn keyword cType DoubleTransientMatParam
-syn keyword cType MatrixParam
-syn keyword cType StringArrayParam
-syn keyword cType StringParam
-syn keyword cType TransientParam
-syn keyword cType OptionStruct
-syn keyword cType OptionDouble
-syn keyword cType OptionLogical
-syn keyword cType OptionUtilities
-syn keyword cType OptionChar
-syn keyword cType Option
-syn keyword cType OptionCell
-syn keyword cType Segment
-syn keyword cType Icefront
-syn keyword cType Friction
-syn keyword cType Riftfront
-syn keyword cType Numericalflux
-syn keyword cType Penpair
-syn keyword cType Load
-syn keyword cType Pengrid
-syn keyword cType Object
-syn keyword cType DoubleVecExternalResult
-syn keyword cType DoubleExternalResult
-syn keyword cType IntExternalResult
-syn keyword cType BoolExternalResult
-syn keyword cType DoubleMatExternalResult
-syn keyword cType PetscVecExternalResult
-syn keyword cType ExternalResult
-syn keyword cType StringExternalResult
-syn keyword cType Vertex
+syn keyword cType DoubleInput
+syn keyword cType TriaInput
+syn keyword cType Constraints
 syn keyword cType SpcDynamic
 syn keyword cType SpcStatic
 syn keyword cType SpcTransient
-syn keyword cType Constraint
-syn keyword cType TriaP1ElementResult
-syn keyword cType PentaP1ElementResult
-syn keyword cType DoubleElementResult
-syn keyword cType ElementResultLocal
-syn keyword cType BoolElementResult
-syn keyword cType ElementResult
+syn keyword cType Nodes
+syn keyword cType IndependentObject
+syn keyword cType Vertices
 syn keyword cType Node
-syn keyword cType TriaRef
-syn keyword cType TriaHook
-syn keyword cType PentaRef
-syn keyword cType PentaHook
-syn keyword cType Tria
-syn keyword cType Element
-syn keyword cType Penta
-syn keyword cType classes
-syn keyword cType DofIndexing
-syn keyword cType Patch
-syn keyword cType Hook
-syn keyword cType Quadtree
-syn keyword cType Observation
-syn keyword cType ExponentialVariogram
-syn keyword cType GaussianVariogram
-syn keyword cType SphericalVariogram
-syn keyword cType PowerVariogram
-syn keyword cType krigingobjects
-syn keyword cType Variogram
-syn keyword cType DakotaPlugin
-syn keyword cType ElementVector
-syn keyword cType ElementMatrix
-syn keyword cType matrixobjects
-syn keyword cType Vector
-syn keyword cType Matrix
-syn keyword cType GeomSubDomain
-syn keyword cType Geometry
-syn keyword cType AdjacentTriangle
-syn keyword cType VertexOnEdge
-syn keyword cType BamgQuadtree
-syn keyword cType Edge
-syn keyword cType BamgVertex
-syn keyword cType SetOfE4
-syn keyword cType GeomEdge
-syn keyword cType Direction
-syn keyword cType VertexOnGeom
-syn keyword cType R2
-syn keyword cType Mesh
-syn keyword cType ListofIntersectionTriangles
-syn keyword cType Triangle
-syn keyword cType DoubleAndInt
-syn keyword cType VertexOnVertex
-syn keyword cType BamgOpts
-syn keyword cType BamgGeom
-syn keyword cType bamgobjects
-syn keyword cType CrackedEdge
-syn keyword cType SubDomain
-syn keyword cType BamgMesh
-syn keyword cType Metric
-syn keyword cType include
-syn keyword cType typedefs
-syn keyword cType Curve
-syn keyword cType macros
-syn keyword cType GeomVertex
-syn keyword cType OptArgs
-syn keyword cType Update
-syn keyword cType OptPars
 syn keyword cType IoModel
 syn keyword cType FemModel
@@ -620,4 +543,7 @@
 syn keyword cConstant DiagnosticVertexPairingEnum
 syn keyword cConstant DiagnosticViscosityOvershootEnum
+syn keyword cConstant LoadingforceXEnum
+syn keyword cConstant LoadingforceYEnum
+syn keyword cConstant LoadingforceZEnum
 syn keyword cConstant FlowequationBordermacayealEnum
 syn keyword cConstant FlowequationBorderpattynEnum
@@ -633,14 +559,46 @@
 syn keyword cConstant FrictionQEnum
 syn keyword cConstant GeometryHydrostaticRatioEnum
-syn keyword cConstant HydrologyCREnum
-syn keyword cConstant HydrologyKnEnum
-syn keyword cConstant HydrologyNEnum
-syn keyword cConstant HydrologyPEnum
-syn keyword cConstant HydrologyQEnum
-syn keyword cConstant HydrologySpcwatercolumnEnum
-syn keyword cConstant HydrologyStabilizationEnum
+syn keyword cConstant HydrologyModelEnum
+syn keyword cConstant HydrologyshreveEnum
+syn keyword cConstant HydrologyshreveCREnum
+syn keyword cConstant HydrologyshreveKnEnum
+syn keyword cConstant HydrologyshreveNEnum
+syn keyword cConstant HydrologyshrevePEnum
+syn keyword cConstant HydrologyshreveQEnum
+syn keyword cConstant HydrologyshreveSpcwatercolumnEnum
+syn keyword cConstant HydrologyshreveStabilizationEnum
+syn keyword cConstant HydrologydcEnum
+syn keyword cConstant SedimentHeadEnum
+syn keyword cConstant SedimentHeadOldEnum
+syn keyword cConstant SedimentHeadResidualEnum
+syn keyword cConstant EplHeadEnum
+syn keyword cConstant EplHeadOldEnum
+syn keyword cConstant HydrologydcRelTolEnum
+syn keyword cConstant HydrologydcSpcsedimentHeadEnum
+syn keyword cConstant HydrologydcSedimentCompressibilityEnum
+syn keyword cConstant HydrologydcSedimentPorosityEnum
+syn keyword cConstant HydrologydcSedimentThicknessEnum
+syn keyword cConstant HydrologydcSedimentTransmitivityEnum
+syn keyword cConstant HydrologydcWaterCompressibilityEnum
+syn keyword cConstant HydrologydcSpceplHeadEnum
+syn keyword cConstant HydrologydcMaskEplactiveEnum
+syn keyword cConstant HydrologydcEplCompressibilityEnum
+syn keyword cConstant HydrologydcEplPorosityEnum
+syn keyword cConstant HydrologydcEplThicknessEnum
+syn keyword cConstant HydrologydcEplTransmitivityEnum
+syn keyword cConstant HydrologydcIsefficientlayerEnum
+syn keyword cConstant HydrologydcSedimentlimitFlagEnum
+syn keyword cConstant HydrologydcSedimentlimitEnum
+syn keyword cConstant HydrologydcTransferFlagEnum
+syn keyword cConstant HydrologydcLeakageFactorEnum
+syn keyword cConstant HydrologydcPenaltyFactorEnum
+syn keyword cConstant HydrologyLayerEnum
+syn keyword cConstant HydrologySedimentEnum
+syn keyword cConstant HydrologyEfficientEnum
+syn keyword cConstant HydrologySedimentKmaxEnum
+syn keyword cConstant BasisIntegralEnum
+syn keyword cConstant WaterTransferEnum
 syn keyword cConstant IndependentObjectEnum
 syn keyword cConstant InversionControlParametersEnum
-syn keyword cConstant InversionCostFunctionEnum
 syn keyword cConstant InversionCostFunctionThresholdEnum
 syn keyword cConstant InversionCostFunctionsCoefficientsEnum
@@ -686,4 +644,8 @@
 syn keyword cConstant MaterialsThermalExchangeVelocityEnum
 syn keyword cConstant MaterialsThermalconductivityEnum
+syn keyword cConstant MaterialsLithosphereShearModulusEnum
+syn keyword cConstant MaterialsLithosphereDensityEnum
+syn keyword cConstant MaterialsMantleShearModulusEnum
+syn keyword cConstant MaterialsMantleDensityEnum
 syn keyword cConstant MeshAverageVertexConnectivityEnum
 syn keyword cConstant MeshDimensionEnum
@@ -751,14 +713,11 @@
 syn keyword cConstant SurfaceforcingsMassBalanceEnum
 syn keyword cConstant SurfaceforcingsIspddEnum
+syn keyword cConstant SurfaceforcingsDesfacEnum
+syn keyword cConstant SurfaceforcingsS0pEnum
 syn keyword cConstant SurfaceforcingsIssmbgradientsEnum
 syn keyword cConstant SurfaceforcingsMonthlytemperaturesEnum
-syn keyword cConstant SurfaceforcingsHcEnum
 syn keyword cConstant SurfaceforcingsHrefEnum
 syn keyword cConstant SurfaceforcingsSmbrefEnum
-syn keyword cConstant SurfaceforcingsSmbPosMaxEnum
-syn keyword cConstant SurfaceforcingsSmbPosMinEnum
-syn keyword cConstant SurfaceforcingsAPosEnum
 syn keyword cConstant SurfaceforcingsBPosEnum
-syn keyword cConstant SurfaceforcingsANegEnum
 syn keyword cConstant SurfaceforcingsBNegEnum
 syn keyword cConstant ThermalMaxiterEnum
@@ -769,4 +728,6 @@
 syn keyword cConstant ThermalStabilizationEnum
 syn keyword cConstant ThermalIsenthalpyEnum
+syn keyword cConstant GiaMantleViscosityEnum
+syn keyword cConstant GiaLithosphereThicknessEnum
 syn keyword cConstant ThicknessEnum
 syn keyword cConstant TimesteppingStartTimeEnum
@@ -779,4 +740,5 @@
 syn keyword cConstant TransientIsprognosticEnum
 syn keyword cConstant TransientIsthermalEnum
+syn keyword cConstant TransientIsgiaEnum
 syn keyword cConstant TransientNumRequestedOutputsEnum
 syn keyword cConstant TransientRequestedOutputsEnum
@@ -788,6 +750,10 @@
 syn keyword cConstant AdjointSolutionEnum
 syn keyword cConstant AnalysisCounterEnum
+syn keyword cConstant NoneAnalysisEnum
+syn keyword cConstant DefaultAnalysisEnum
 syn keyword cConstant BalancethicknessAnalysisEnum
 syn keyword cConstant BalancethicknessSolutionEnum
+syn keyword cConstant WeakBalancethicknessAnalysisEnum
+syn keyword cConstant WeakBalancethicknessSolutionEnum
 syn keyword cConstant BedSlopeAnalysisEnum
 syn keyword cConstant BedSlopeSolutionEnum
@@ -802,8 +768,9 @@
 syn keyword cConstant FlaimAnalysisEnum
 syn keyword cConstant FlaimSolutionEnum
-syn keyword cConstant HydrologyAnalysisEnum
+syn keyword cConstant HydrologyShreveAnalysisEnum
+syn keyword cConstant HydrologyDCInefficientAnalysisEnum
+syn keyword cConstant HydrologyDCEfficientAnalysisEnum
 syn keyword cConstant HydrologySolutionEnum
 syn keyword cConstant MeltingAnalysisEnum
-syn keyword cConstant NoneAnalysisEnum
 syn keyword cConstant PrognosticAnalysisEnum
 syn keyword cConstant PrognosticSolutionEnum
@@ -816,4 +783,6 @@
 syn keyword cConstant ThermalSolutionEnum
 syn keyword cConstant TransientSolutionEnum
+syn keyword cConstant GiaSolutionEnum
+syn keyword cConstant GiaAnalysisEnum
 syn keyword cConstant ApproximationEnum
 syn keyword cConstant NoneApproximationEnum
@@ -830,4 +799,5 @@
 syn keyword cConstant MaterialsEnum
 syn keyword cConstant NodesEnum
+syn keyword cConstant ContoursEnum
 syn keyword cConstant ParametersEnum
 syn keyword cConstant VerticesEnum
@@ -858,4 +828,5 @@
 syn keyword cConstant IntVecParamEnum
 syn keyword cConstant TransientParamEnum
+syn keyword cConstant IceFrontTypeEnum
 syn keyword cConstant MacAyeal2dIceFrontEnum
 syn keyword cConstant MacAyeal3dIceFrontEnum
@@ -865,4 +836,5 @@
 syn keyword cConstant NodeEnum
 syn keyword cConstant NumericalfluxEnum
+syn keyword cConstant NumericalfluxTypeEnum
 syn keyword cConstant ParamEnum
 syn keyword cConstant L1L2IceFrontEnum
@@ -874,6 +846,8 @@
 syn keyword cConstant ProfilerEnum
 syn keyword cConstant MatrixParamEnum
+syn keyword cConstant NodeSIdEnum
 syn keyword cConstant VectorParamEnum
 syn keyword cConstant RiftfrontEnum
+syn keyword cConstant RiftfrontTypeEnum
 syn keyword cConstant SegmentEnum
 syn keyword cConstant SegmentRiftfrontEnum
@@ -885,6 +859,8 @@
 syn keyword cConstant StringParamEnum
 syn keyword cConstant TriaEnum
-syn keyword cConstant TriaP1InputEnum
+syn keyword cConstant TriaInputEnum
 syn keyword cConstant VertexEnum
+syn keyword cConstant VertexPIdEnum
+syn keyword cConstant VertexSIdEnum
 syn keyword cConstant AirEnum
 syn keyword cConstant IceEnum
@@ -898,4 +874,5 @@
 syn keyword cConstant AdjointyEnum
 syn keyword cConstant AdjointzEnum
+syn keyword cConstant BalancethicknessMisfitEnum
 syn keyword cConstant BedSlopeXEnum
 syn keyword cConstant BedSlopeYEnum
@@ -903,5 +880,4 @@
 syn keyword cConstant ConstantEnum
 syn keyword cConstant ConvergedEnum
-syn keyword cConstant ExtToIuEnum
 syn keyword cConstant FillEnum
 syn keyword cConstant FractionIncrementEnum
@@ -909,5 +885,4 @@
 syn keyword cConstant GroundinglineMeltingRateEnum
 syn keyword cConstant InternalEnum
-syn keyword cConstant IuToExtEnum
 syn keyword cConstant MassFluxEnum
 syn keyword cConstant MaxPenetrationEnum
@@ -925,4 +900,5 @@
 syn keyword cConstant QmuSurfaceEnum
 syn keyword cConstant QmuMeltingEnum
+syn keyword cConstant AndroidFrictionCoefficientEnum
 syn keyword cConstant ResetPenaltiesEnum
 syn keyword cConstant SegmentOnIceShelfEnum
@@ -938,8 +914,5 @@
 syn keyword cConstant TemperatureOldEnum
 syn keyword cConstant TemperaturePicardEnum
-syn keyword cConstant TemperatureSurfaceEnum
-syn keyword cConstant TemperatureBasalEnum
 syn keyword cConstant ThicknessAbsMisfitEnum
-syn keyword cConstant TypeEnum
 syn keyword cConstant VelEnum
 syn keyword cConstant VelocityEnum
@@ -968,5 +941,4 @@
 syn keyword cConstant DragCoefficientAbsGradientEnum
 syn keyword cConstant TransientInputEnum
-syn keyword cConstant OutputfilenameEnum
 syn keyword cConstant WaterfractionEnum
 syn keyword cConstant WatercolumnEnum
@@ -983,7 +955,12 @@
 syn keyword cConstant StressTensoryzEnum
 syn keyword cConstant StressTensorzzEnum
+syn keyword cConstant GiaCrossSectionShapeEnum
+syn keyword cConstant GiadWdtEnum
+syn keyword cConstant GiaWEnum
 syn keyword cConstant P0Enum
 syn keyword cConstant P1Enum
 syn keyword cConstant P1DGEnum
+syn keyword cConstant MINIEnum
+syn keyword cConstant P2Enum
 syn keyword cConstant SaveResultsEnum
 syn keyword cConstant BoolElementResultEnum
@@ -992,5 +969,4 @@
 syn keyword cConstant DoubleExternalResultEnum
 syn keyword cConstant DoubleMatExternalResultEnum
-syn keyword cConstant DoubleVecExternalResultEnum
 syn keyword cConstant IntExternalResultEnum
 syn keyword cConstant JEnum
@@ -999,5 +975,4 @@
 syn keyword cConstant PatchVerticesEnum
 syn keyword cConstant PentaP1ElementResultEnum
-syn keyword cConstant PetscVecExternalResultEnum
 syn keyword cConstant StringExternalResultEnum
 syn keyword cConstant StepEnum
@@ -1018,5 +993,4 @@
 syn keyword cConstant IceVolumeEnum
 syn keyword cConstant TotalSmbEnum
-syn keyword cConstant RelativeEnum
 syn keyword cConstant AbsoluteEnum
 syn keyword cConstant IncrementalEnum
@@ -1024,4 +998,7 @@
 syn keyword cConstant NoneEnum
 syn keyword cConstant SoftMigrationEnum
+syn keyword cConstant SubelementMigrationEnum
+syn keyword cConstant SubelementMigration2Enum
+syn keyword cConstant GLlevelsetEnum
 syn keyword cConstant StokesSolverEnum
 syn keyword cConstant AdjointEnum
@@ -1043,6 +1020,6 @@
 syn keyword cConstant OutputFileNameEnum
 syn keyword cConstant LockFileNameEnum
-syn keyword cConstant PetscOptionsAnalysesEnum
-syn keyword cConstant PetscOptionsStringsEnum
+syn keyword cConstant ToolkitsOptionsAnalysesEnum
+syn keyword cConstant ToolkitsOptionsStringsEnum
 syn keyword cConstant QmuErrNameEnum
 syn keyword cConstant QmuInNameEnum
@@ -1058,4 +1035,8 @@
 syn keyword cConstant XYEnum
 syn keyword cConstant XYZPEnum
+syn keyword cConstant DenseEnum
+syn keyword cConstant MpiDenseEnum
+syn keyword cConstant SeqEnum
+syn keyword cConstant MpiEnum
 syn keyword cConstant OptionEnum
 syn keyword cConstant GenericOptionEnum
Index: /issm/trunk/externalpackages/vim/addons/vimrc
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vimrc	(revision 15395)
+++ /issm/trunk/externalpackages/vim/addons/vimrc	(revision 15396)
@@ -194,34 +194,34 @@
 " Abbreviations {{{
 " ----------------------------------------------------------------------
-"func Eatchar(pat)
-"	let c = nr2char(getchar())
-"	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);"
-""tex
-"au BufRead,BufNewFile *.tex iab EQ 
-"			\\begin{equation}
-"			\<CR>\end{equation}<up><C-R>=Eatchar('\s')<CR>
-"au BufRead,BufNewFile *.tex iab IT 
-"			\\begin{itemize}
-"			\<CR>\item 
-"			\<CR>\end{itemize}<up><C-R>=Eatchar('\s')<CR>
-"au BufRead,BufNewFile *.tex iab EN 
-"			\\begin{enumerate}
-"			\<CR>\item 
-"			\<CR>\end{enumerate}<up><C-R>=Eatchar('\s')<CR>
-"au BufRead,BufNewFile *.tex ab (()) \left( \right)
+func Eatchar(pat)
+	let c = nr2char(getchar())
+	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);"
+"tex
+au BufRead,BufNewFile *.tex iab EQ 
+			\\begin{equation}
+			\<CR>\end{equation}<up><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.tex iab IT 
+			\\begin{itemize}
+			\<CR>\item 
+			\<CR>\end{itemize}<up><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.tex iab EN 
+			\\begin{enumerate}
+			\<CR>\item 
+			\<CR>\end{enumerate}<up><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.tex ab (()) \left( \right)
 "}}}
 " Skeletons {{{
Index: /issm/trunk/externalpackages/vim/install.sh
===================================================================
--- /issm/trunk/externalpackages/vim/install.sh	(revision 15395)
+++ /issm/trunk/externalpackages/vim/install.sh	(revision 15396)
@@ -23,6 +23,7 @@
 cd src/src 
 ./configure \
-	--prefix "$ISSM_DIR/externalpackages/vim/install" \
-	--with-gcc "/usr/bin/gcc"
+	--prefix="$ISSM_DIR/externalpackages/vim/install" \
+	--with-gcc="/usr/bin/gcc" \
+	--with-tlib="/lib/"
 
 #Compile vim
Index: /issm/trunk/externalpackages/windows/README
===================================================================
--- /issm/trunk/externalpackages/windows/README	(revision 15395)
+++ /issm/trunk/externalpackages/windows/README	(revision 15396)
@@ -51,2 +51,21 @@
 
 We'll try the compile with the Microsoft Windows SDK 7.1: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=8279
+
+
+
+MPICH2: 
+to run in parallel.  First install MPICH2 from www.mpich.org/downloads. Make 
+sure the install directory in C:\Program Files\MPICH2, otherwise, ISSM will 
+not be able to figure out where the mpi libraries are installed on your windows platform.
+
+Then fire up smpd in a command line under Administrator privileges: 
+smpd -install
+
+Then: 
+mpiexe.exe -remove
+mpiexe.exe -register (type enter for username, for password, type your windows password, do not chose anything else!)
+mpiexe.exe -validate (should return SUCCESS)
+
+Then you are ready to run parallel.
+
+To do: how do we document this? Create webpage for all of this. + get a fortran compiler giong!
Index: /issm/trunk/externalpackages/windows/fortran_environment.sh
===================================================================
--- /issm/trunk/externalpackages/windows/fortran_environment.sh	(revision 15396)
+++ /issm/trunk/externalpackages/windows/fortran_environment.sh	(revision 15396)
@@ -0,0 +1,70 @@
+declare -x APPDATA="C:\Users\larour\AppData\Roaming"
+declare -x ARCH_PATH="ia32"
+declare -x ARCH_PATH_MPI="ia32"
+declare -x BIN_ROOT="C:\Program Files (x86)\Intel\Composer XE 2013\bin"
+declare -x BUNDLE_NAME="Intel(R) Parallel Studio XE 2013"
+declare -x COMMONPROGRAMFILES="C:\Program Files (x86)\Common Files"
+declare -x CommonProgramW6432="C:\Program Files\Common Files"
+declare -x COMPUTERNAME="WIN-BBO0CI1DTAL"
+declare -x COMSPEC="C:\Windows\system32\cmd.exe"
+declare -x C_TARGET_ARCH="ia32"
+declare -x DevEnvDir="C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE"
+declare -x FP_NO_HOST_CHECK="NO"
+declare -x Framework35Version="v3.5"
+declare -x FrameworkDir="C:\Windows\Microsoft.NET\Framework"
+declare -x FrameworkDIR32="C:\Windows\Microsoft.NET\Framework"
+declare -x FrameworkVersion="v4.0.30319"
+declare -x FrameworkVersion32="v4.0.30319"
+declare -x HOMEDRIVE="C:"
+declare -x HOMEPATH="\Users\larour"
+declare -x IFORT_COMPILER13="C:\Program Files (x86)\Intel\Composer XE 2013"
+declare -x INCLUDE="C:\Program Files (x86)\Intel\Composer XE 2013\compiler\include;C:\Program Files (x86)\Intel\Composer XE 2013\compiler\include\ia32;C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE;C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\include;C:\Program Files (x86)\Intel\Composer XE 2013\mkl\include;"
+declare -x INTEL_DEV_REDIST="C:\Program Files (x86)\Common Files\Intel\Shared Libraries"
+declare -x INTEL_LICENSE_FILE="C:\Program Files (x86)\Common Files\Intel\Licenses"
+declare -x LIB="C:\Program Files (x86)\Intel\Composer XE 2013\compiler\lib;C:\Program Files (x86)\Intel\Composer XE 2013\compiler\lib\ia32;C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\LIB;C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\lib;C:\Program Files (x86)\Intel\Composer XE 2013\mkl\lib\ia32;C:\Program Files (x86)\Intel\Composer XE 2013\compiler\lib\ia32;"
+declare -x LIBPATH="C:\Windows\Microsoft.NET\Framework\v4.0.30319;C:\Windows\Microsoft.NET\Framework\v3.5;C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\LIB;"
+declare -x LOCALAPPDATA="C:\Users\larour\AppData\Local"
+declare -x LOGONSERVER="\\WIN-BBO0CI1DTAL"
+declare -x MKLROOT="C:\Program Files (x86)\Intel\Composer XE 2013\mkl"
+declare -x MSVS_VAR_SCRIPT="C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\..\..\VC\vcvarsall.bat"
+declare -x NUMBER_OF_PROCESSORS="8"
+declare -x OS="Windows_NT"
+declare -x PATH="$PATH:/cygdrive/c/Program Files (x86)/Intel/Composer XE 2013/bin/ia32:/cygdrive/c/Program Files (x86)/Intel/Composer XE 2013/redist/ia32/compiler:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/Common7/IDE:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/VC/BIN:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/Common7/Tools:/cygdrive/c/Windows/Microsoft.NET/Framework/v4.0.30319:/cygdrive/c/Windows/Microsoft.NET/Framework/v3.5:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/VC/VCPackages:/cygdrive/c/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/bin/NETFX 4.0 Tools:/cygdrive/c/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/bin:/cygdrive/c/Program Files (x86)/Intel/Composer XE 2013/redist/ia32/mkl:/cygdrive/c/Program Files (x86)/Intel/Composer XE 2013/redist/ia32/compiler:/cygdrive/c/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64/mpirt:/cygdrive/c/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64/compiler:/cygdrive/c/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/ia32/mpirt:/cygdrive/c/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/ia32/compiler:/cygdrive/c/Windows/system32:/cygdrive/c/Windows:/cygdrive/c/Windows/System32/Wbem:/cygdrive/c/Windows/System32/WindowsPowerShell/v1.0:/cygdrive/c/Program Files/Microsoft Windows Performance Toolkit:/cygdrive/c/MATLAB/R2012b/runtime/win64:/cygdrive/c/MATLAB/R2012b/bin:/cygdrive/c/Program Files (x86)/Intel/Composer XE 2013/redist/ia32/mpirt"
+declare -x PATHEXT=".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC"
+declare -x PROCESSOR_ARCHITECTURE="x86"
+declare -x PROCESSOR_ARCHITEW6432="AMD64"
+declare -x PROCESSOR_IDENTIFIER="Intel64 Family 6 Model 58 Stepping 9, GenuineIntel"
+declare -x PROCESSOR_LEVEL="6"
+declare -x PROCESSOR_REVISION="3a09"
+declare -x PRODUCT_NAME="Intel Composer XE 2013 "
+declare -x PRODUCT_NAME_FULL="Intel(R) Composer XE 2013 Update 3 (package 171)"
+declare -x ProgramData="C:\ProgramData"
+declare -x PROGRAMFILES="C:\Program Files (x86)"
+declare -x ProgramW6432="C:\Program Files"
+declare -x PROMPT="$P$G"
+declare -x protector_attach="true"
+declare -x PSModulePath="C:\Windows\system32\WindowsPowerShell\v1.0\Modules"
+declare -x PUBLIC="C:\Users\Public"
+declare -x ROOT="C:\Program Files (x86)\Intel\Composer XE 2013"
+declare -x SCRIPT_NAME="compilervars_arch.bat"
+declare -x SESSIONNAME="Console"
+declare -x SYSTEMDRIVE="C:"
+declare -x SYSTEMROOT="C:\Windows"
+declare -x TARGET_ARCH="ia32"
+declare -x TARGET_VS="vs2010"
+declare -x TARGET_VS_ARCH="x86"
+declare -x TEMP="/cygdrive/c/Users/larour/AppData/Local/Temp"
+declare -x TMP="/cygdrive/c/Users/larour/AppData/Local/Temp"
+declare -x USERDOMAIN="WIN-BBO0CI1DTAL"
+declare -x USERNAME="larour"
+declare -x USERPROFILE="C:\Users\larour"
+declare -x VCINSTALLDIR="C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC"
+declare -x VS100COMNTOOLS="C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools"
+declare -x VSINSTALLDIR="C:\Program Files (x86)\Microsoft Visual Studio 10.0"
+declare -x WINDIR="C:\Windows"
+declare -x WindowsSdkDir="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A"
+declare -x windows_tracing_flags="3"
+declare -x windows_tracing_logfile="C:\BVTBin\Tests\installpackage\csilogfile.log"
+declare -x WIN_TITLE="Intel Composer XE 2013  IA-32 Visual Studio 2010"
+declare -x WIN_TITLE_ARCH="IA-32"
+declare -x WIN_TITLE_VS="Visual Studio 2010"
Index: /issm/trunk/externalpackages/windows/windows_environment.sh
===================================================================
--- /issm/trunk/externalpackages/windows/windows_environment.sh	(revision 15395)
+++ /issm/trunk/externalpackages/windows/windows_environment.sh	(revision 15396)
@@ -37,2 +37,5 @@
 ISSM_DIR_WIN=`cygpath -m $ISSM_DIR`
 export ISSM_DIR_WIN
+
+#Now source for fortran environment: 
+#source $ISSM_DIR/externalpackages/windows/fortran_environment.sh
Index: /issm/trunk/m4/ar-lib.m4
===================================================================
--- /issm/trunk/m4/ar-lib.m4	(revision 15396)
+++ /issm/trunk/m4/ar-lib.m4	(revision 15396)
@@ -0,0 +1,61 @@
+##                                                          -*- Autoconf -*-
+# Copyright (C) 2011-2012 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 1
+
+# AM_PROG_AR([ACT-IF-FAIL])
+# -------------------------
+# Try to determine the archiver interface, and trigger the ar-lib wrapper
+# if it is needed.  If the detection of archiver interface fails, run
+# ACT-IF-FAIL (default is to abort configure with a proper error message).
+AC_DEFUN([AM_PROG_AR],
+[AC_BEFORE([$0], [LT_INIT])dnl
+AC_BEFORE([$0], [AC_PROG_LIBTOOL])dnl
+AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
+AC_REQUIRE_AUX_FILE([ar-lib])dnl
+AC_CHECK_TOOLS([AR], [ar lib "link -lib"], [false])
+: ${AR=ar}
+
+AC_CACHE_CHECK([the archiver ($AR) interface], [am_cv_ar_interface],
+  [am_cv_ar_interface=ar
+   AC_COMPILE_IFELSE([AC_LANG_SOURCE([[int some_variable = 0;]])],
+     [am_ar_try='$AR cru libconftest.a conftest.$ac_objext >&AS_MESSAGE_LOG_FD'
+      AC_TRY_EVAL([am_ar_try])
+      if test "$ac_status" -eq 0; then
+        am_cv_ar_interface=ar
+      else
+        am_ar_try='$AR -NOLOGO -OUT:conftest.lib conftest.$ac_objext >&AS_MESSAGE_LOG_FD'
+        AC_TRY_EVAL([am_ar_try])
+        if test "$ac_status" -eq 0; then
+          am_cv_ar_interface=lib
+        else
+          am_cv_ar_interface=unknown
+        fi
+      fi
+      rm -f conftest.lib libconftest.a
+     ])
+   ])
+
+case $am_cv_ar_interface in
+ar)
+  ;;
+lib)
+  # Microsoft lib, so override with the ar-lib wrapper script.
+  # FIXME: It is wrong to rewrite AR.
+  # But if we don't then we get into trouble of one sort or another.
+  # A longer-term fix would be to have automake use am__AR in this case,
+  # and then we could set am__AR="$am_aux_dir/ar-lib \$(AR)" or something
+  # similar.
+  AR="$am_aux_dir/ar-lib $AR"
+  ;;
+unknown)
+  m4_default([$1],
+             [AC_MSG_ERROR([could not determine $AR interface])])
+  ;;
+esac
+AC_SUBST([AR])dnl
+])
Index: /issm/trunk/m4/issm_options.m4
===================================================================
--- /issm/trunk/m4/issm_options.m4	(revision 15395)
+++ /issm/trunk/m4/issm_options.m4	(revision 15396)
@@ -55,19 +55,21 @@
 			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_"
 		elif  test $VENDOR = intel-win7-32; then
-			export CC=cccl
+			export CC=cl
 			export CXX=cccl
 			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
 			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
-			export AR=lib
+			export AR="ar-lib lib"
+			export OS_LDFLAG="-Wl,"
 			export RANLIB=true
-			OSLIBS="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"
+			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=cccl
+			export CC=cl
 			export CXX=cccl
 			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
 			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
-			export AR=lib
+			export AR="ar-lib lib"
+			export OS_LDFLAG="-Wl,"
 			export RANLIB=true
-			OSLIBS="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"
+			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
@@ -83,8 +85,8 @@
 			export CC=icc
 			export CXX=icpc
-			export CXXFLAGS=" -O3 -xS -D_INTEL_LINUX_ "
-			export CFLAGS=" -O3 -xS -D_INTEL_LINUX_ "
+			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ "
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ "
         else
-		AC_MSG_ERROR([unknow compiler vendor!])
+		AC_MSG_ERROR([unknown compiler vendor!])
 		fi
 	fi
@@ -115,10 +117,26 @@
 
 		AC_MSG_CHECKING(for matlab headers and libraries in $MATLAB_ROOT)
-		MATLABINCL=-I"$MATLAB_ROOT/extern/include";
+  		MATLABINCL="-I$MATLAB_ROOT/extern/include/"
 		
 		dnl 4. get MEXLIB MEXLINK and MEXEXT (experimental)
-		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")
+      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)
 
@@ -127,5 +145,5 @@
 		MATLABWRAPPEREXT=$MEXEXT
 		AC_SUBST([MATLABWRAPPEREXT])
-	    AC_SUBST([MEXLIB]) 
+	   AC_SUBST([MEXLIB]) 
 		AC_SUBST([MEXLINK])
 	fi
@@ -145,5 +163,5 @@
 		case "${host_os}" in
 				*cygwin*)
-				TRIANGLELIB=$TRIANGLE_ROOT/triangle.lib
+				TRIANGLELIB="-Wl,`cygpath -m $TRIANGLE_ROOT/`triangle.lib"
 				;;
 				*linux*)
@@ -177,10 +195,19 @@
 		DAKOTAINCL=-I$DAKOTA_ROOT/include
 		AC_MSG_CHECKING(for dakota version)
-		DAKOTA_VERSION=`cat $DAKOTA_ROOT/include/dakota_config.h | grep "#define PACKAGE_VERSION" | sed 's/#define PACKAGE_VERSION//' | sed 's/ //g' | sed -e 's/\"//g' `
+		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])
+		AC_DEFINE_UNQUOTED([_DAKOTA_VERSION_],"$DAKOTA_VERSION",[Dakota version number])
+		DAKOTAFLAGS=""
 		case "${host_os}" in
 			*cygwin*)
-				if      test x$DAKOTA_VERSION = x4.2; then
+				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
@@ -192,15 +219,19 @@
 			;;
 			*linux*)
-				if      test x$DAKOTA_VERSION = x4.2; then
+				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"
+					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"
 				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; then
+				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"
@@ -215,5 +246,37 @@
 		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])
 
@@ -222,4 +285,5 @@
 		AC_MSG_RESULT($HAVE_DAKOTA)
 	fi
+
 	AM_CONDITIONAL([DAKOTA], [test x$HAVE_DAKOTA = xyes])
 	dnl }}}
@@ -478,26 +542,45 @@
 	dnl mpi{{{
 	AC_MSG_CHECKING(for mpi)
-	AC_ARG_WITH([mpi-lib],
-		AS_HELP_STRING([--with-mpi-lib = options],[mpi options, for ex: "-L$MPIROOT -lmpich]),
-		[MPILIB=$withval],[MPILIB=""])
 	
 	AC_ARG_WITH([mpi-include],
 	  AS_HELP_STRING([--with-mpi-include=DIR],[mpi include directory, necessary for parallel build]),
 	  [MPI_INCLUDE=$withval],[MPI_INCLUDE=""])
-	
-	if test -z "$MPILIB" ; then
+
+	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
-		if test -z "$MPI_INCLUDE" ; then
-			HAVE_MPI=no
+		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
-			HAVE_MPI=yes
 			MPIINCL=-I"$MPI_INCLUDE"
-			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
-	fi
+			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)
@@ -517,7 +600,10 @@
 
 		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)
-		if test x$PETSC_VERSION_DATE_HG = xunknown; then
-			AC_DEFINE([_HAVE_PETSCDEV_],[1],[with PETSc-dev])
+		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
@@ -549,13 +635,13 @@
 			*cygwin*)
 			if test $PETSC_MAJOR -lt 3 ; then
-				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/lib\" libpetscksp.lib libpetscdm.lib libpetscmat.lib libpetscvec.lib libpetscsnes.lib libpetscts.lib libmpiuni.lib libpetsc.lib"
+				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="-link -LIBPATH:\"$PETSC_ROOT/lib\" libpetsc.lib"
-				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" libmetis.lib"; fi
+				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 -lpetsc  -lpetscsnes -lpetscts"
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lmpiuni -lpetsc"
 			else
 				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc -ldl"
@@ -614,5 +700,5 @@
 				case "${host_os}" in
 					*cygwin*)
-					METISLIB="-LIBPATH:\"$METIS_ROOT\" libmetis.lib"
+					METISLIB="-L$METIS_ROOT -Wl,libmetis.lib"
 					;;
 					*linux*)
@@ -630,5 +716,5 @@
 				case "${host_os}" in
 					*cygwin*)
-					METISLIB="-LIBPATH:\"$METIS_ROOT\" libmetis.lib"
+					METISLIB="-L$METIS_ROOT libmetis.lib"
 					;;
 					*linux*)
@@ -755,11 +841,11 @@
 		case "${host_os}" in
 			*cygwin*)
-			BLASLAPACKLIB="-link -LIBPATH:\"$BLASLAPACK_ROOT\" libf2cblas.lib  libf2clapack.lib"
+			BLASLAPACKLIB="-L`cygpath -m $BLASLAPACK_ROOT` -Wl,libf2cblas.lib  -Wl,libf2clapack.lib"
 			;;
 			*linux*)
-			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lflapack -lfblas " 
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
 			;;
 			*darwin*)
-			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lflapack -lfblas " 
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
 			;;
 		esac
@@ -785,5 +871,9 @@
 		HAVE_MKL=yes
 		MKLINCL=""
-		MKLLIB=-L"$MKL_ROOT -lmkl -lmkl_lapack -lmkl_scalapack_ilp64   -lmkl_blacs_sgimpt_ilp64 -lguide  -lpthread"
+		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])
@@ -849,4 +939,5 @@
 		HAVE_MUMPS=no
 	fi
+	AM_CONDITIONAL([MUMPS], [test x$HAVE_MUMPS = xyes])
 	AC_MSG_RESULT($HAVE_MUMPS)
 	dnl }}}
@@ -1012,6 +1103,6 @@
 		dnl defaults
 		HAVE_ML=yes
-		MLINCL=""
-		MLLIB=-L"$ML_ROOT/ -lml"
+		MLINCL=-I"$ML_ROOT/include"
+		MLLIB=-L"$ML_ROOT/lib -lml"
         
 		AC_DEFINE([_HAVE_ML_],[1],[with Blacs in ISSM src])
@@ -1023,5 +1114,26 @@
 	AC_MSG_RESULT($HAVE_ML)
 	dnl }}}
-	dnl math{{{
+	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],
@@ -1077,5 +1189,5 @@
 				fi
 			 fi
-				AC_MSG_ERROR([frtran library provided ($FORTRAN_LIB$) does not exist!]);
+				AC_MSG_ERROR([fortran library provided ($FORTRAN_LIB) does not exist!]);
 			fi
 		fi
@@ -1356,4 +1468,64 @@
 	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{{{
Index: /issm/trunk/packagers/win7/ISSM.initial.aip
===================================================================
--- /issm/trunk/packagers/win7/ISSM.initial.aip	(revision 15395)
+++ /issm/trunk/packagers/win7/ISSM.initial.aip	(revision 15396)
@@ -1,4 +1,4 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<DOCUMENT Type="Advanced Installer" CreateVersion="8.9" version="8.9" Modules="simple" RootPath="." Language="en" Id="{36DC7549-63BC-4A22-AE82-A96C27BF7B21}">
+<DOCUMENT Type="Advanced Installer" CreateVersion="8.9" version="10.1" Modules="simple" RootPath="." Language="en" Id="{36DC7549-63BC-4A22-AE82-A96C27BF7B21}">
   <COMPONENT cid="caphyon.advinst.msicomp.MsiPropsComponent">
     <ROW Property="ALLUSERS" Value="2"/>
@@ -12,5 +12,5 @@
     <ROW Property="ProductLanguage" Value="1033"/>
     <ROW Property="ProductName" Value="ISSM" ValueLocId="*"/>
-    <ROW Property="ProductVersion" Value="1.0"/>
+    <ROW Property="ProductVersion" Value="1.0" Type="32"/>
     <ROW Property="SecureCustomProperties" Value="OLDPRODUCTS;AI_NEWERPRODUCTFOUND"/>
     <ROW Property="UpgradeCode" Value="{F12D1A74-5079-41A3-A02A-15754B89E390}"/>
@@ -58,4 +58,6 @@
     <ROW Fragment="CommonUI.aip" Path="&lt;AI_FRAGS&gt;CommonUI.aip"/>
     <ROW Fragment="FolderDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\FolderDlg.aip"/>
+    <ROW Fragment="MaintenanceTypeDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\MaintenanceTypeDlg.aip"/>
+    <ROW Fragment="MaintenanceWelcomeDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\MaintenanceWelcomeDlg.aip"/>
     <ROW Fragment="SequenceDialogs.aip" Path="&lt;AI_THEMES&gt;classic\fragments\SequenceDialogs.aip"/>
     <ROW Fragment="Sequences.aip" Path="&lt;AI_FRAGS&gt;Sequences.aip"/>
@@ -63,4 +65,7 @@
     <ROW Fragment="UI.aip" Path="&lt;AI_THEMES&gt;classic\fragments\UI.aip"/>
     <ROW Fragment="Validation.aip" Path="&lt;AI_FRAGS&gt;Validation.aip"/>
+    <ROW Fragment="VerifyRemoveDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\VerifyRemoveDlg.aip"/>
+    <ROW Fragment="VerifyRepairDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\VerifyRepairDlg.aip"/>
+    <ROW Fragment="WelcomeDlg.aip" Path="&lt;AI_THEMES&gt;classic\fragments\WelcomeDlg.aip"/>
   </COMPONENT>
   <COMPONENT cid="caphyon.advinst.msicomp.MsiBinaryComponent">
@@ -87,4 +92,10 @@
     <ROW Dialog_="VerifyReadyDlg" Control_="Install" Event="EndDialog" Argument="Return" Condition="AI_PATCH" Ordering="199"/>
     <ROW Dialog_="ResumeDlg" Control_="Install" Event="EndDialog" Argument="Return" Condition="AI_RESUME" Ordering="299"/>
+    <ROW Dialog_="VerifyRemoveDlg" Control_="Remove" Event="EndDialog" Argument="Return" Condition="AI_MAINT AND InstallMode = &quot;Remove&quot;" Ordering="299"/>
+    <ROW Dialog_="VerifyRepairDlg" Control_="Repair" Event="EndDialog" Argument="Return" Condition="AI_MAINT AND InstallMode = &quot;Repair&quot;" Ordering="399"/>
+    <ROW Dialog_="VerifyRemoveDlg" Control_="Back" Event="NewDialog" Argument="MaintenanceTypeDlg" Condition="AI_MAINT AND InstallMode = &quot;Remove&quot;" Ordering="1"/>
+    <ROW Dialog_="VerifyRepairDlg" Control_="Back" Event="NewDialog" Argument="MaintenanceTypeDlg" Condition="AI_MAINT AND InstallMode = &quot;Repair&quot;" Ordering="1"/>
+    <ROW Dialog_="MaintenanceTypeDlg" Control_="RemoveButton" Event="NewDialog" Argument="VerifyRemoveDlg" Condition="AI_MAINT AND InstallMode = &quot;Remove&quot;" Ordering="601"/>
+    <ROW Dialog_="MaintenanceTypeDlg" Control_="RepairButton" Event="NewDialog" Argument="VerifyRepairDlg" Condition="AI_MAINT AND InstallMode = &quot;Repair&quot;" Ordering="601"/>
   </COMPONENT>
   <COMPONENT cid="caphyon.advinst.msicomp.MsiCreateFolderComponent">
@@ -98,4 +109,5 @@
     <ROW Action="AI_RESTORE_LOCATION" Type="65" Source="aicustact.dll" Target="RestoreLocation"/>
     <ROW Action="AI_ResolveKnownFolders" Type="1" Source="aicustact.dll" Target="AI_ResolveKnownFolders"/>
+    <ROW Action="AI_ResolveLocalizedCredentials" Type="1" Source="aicustact.dll" Target="GetLocalizedCredentials"/>
     <ROW Action="AI_SHOW_LOG" Type="65" Source="aicustact.dll" Target="LaunchLogFile" WithoutSeq="true"/>
     <ROW Action="AI_STORE_LOCATION" Type="51" Source="ARPINSTALLLOCATION" Target="[APPDIR]"/>
@@ -118,11 +130,14 @@
     <ROW Action="AI_STORE_LOCATION" Condition="(Not Installed) OR REINSTALL" Sequence="1501"/>
     <ROW Action="AI_PREPARE_UPGRADE" Condition="AI_UPGRADE=&quot;No&quot; AND (Not Installed)" Sequence="1399"/>
-    <ROW Action="AI_ResolveKnownFolders" Sequence="51"/>
+    <ROW Action="AI_ResolveKnownFolders" Sequence="52"/>
+    <ROW Action="AI_ResolveLocalizedCredentials" Sequence="51"/>
   </COMPONENT>
   <COMPONENT cid="caphyon.advinst.msicomp.MsiInstallUISequenceComponent">
     <ROW Action="AI_RESTORE_LOCATION" Condition="APPDIR=&quot;&quot;" Sequence="749"/>
-    <ROW Action="AI_ResolveKnownFolders" Sequence="51"/>
+    <ROW Action="AI_ResolveKnownFolders" Sequence="52"/>
+    <ROW Action="AI_ResolveLocalizedCredentials" Sequence="51"/>
   </COMPONENT>
   <COMPONENT cid="caphyon.advinst.msicomp.MsiLaunchConditionsComponent">
+    <ROW Condition="Privileged" Description="[ProductName] requires administrative privileges to install." DescriptionLocId="AI.LaunchCondition.Privileged" IsPredefined="true" Builds="DefaultBuild"/>
     <ROW Condition="VersionNT" Description="[ProductName] cannot be installed on [WindowsType9XDisplay]" DescriptionLocId="AI.LaunchCondition.No9X" IsPredefined="true" Builds="DefaultBuild"/>
   </COMPONENT>
Index: sm/trunk/packagers/win7/package.sh
===================================================================
--- /issm/trunk/packagers/win7/package.sh	(revision 15395)
+++ 	(revision )
@@ -1,38 +1,0 @@
-#!/bin/bash
-
-#get brand new project: 
-rm -rf ISSM.aip  ISSM-SetupFiles ISSM.msi
-cp ISSM.initial.aip ISSM.aip
-
-#get windows style path to files
-ISSM_TIER_WIN=`cygpath -m "$ISSM_TIER"`
-
-#build list of files to put into the installer: 
-rm -rf ISSM.aic 
-cat << END > ISSM.aic
-;aic
-SetVersion "1.0"
-SetPackageName "ISSM.msi"
-END
-
-ls $ISSM_TIER_WIN/scripts/*.bat startup.m $ISSM_TIER_WIN/bin/*.h | awk '{printf("AddFile APPDIR %s\n",$1);}' | sed 's/\//\\/g' >> ISSM.aic
-
-cat << END >> ISSM.aic
-AddFolder PersonalFolder $ISSM_TIER_WIN\test
-AddFolder APPDIR $ISSM_TIER_WIN\bin
-DelEnvironment ISSM_TESTS
-NewEnvironment -name ISSM_TESTS -value [test_Dir]
-DelEnvironment ISSM_TIER
-NewEnvironment -name ISSM_TIER -value [APPDIR]
-DelEnvironment ISSM_TIER_WIN
-NewEnvironment -name ISSM_TIER_WIN -value [APPDIR]
-Save
-Rebuild
-END
-
-#Run installer: 
-"C:/Program Files (x86)/Caphyon/Advanced Installer 8.9/bin/x86/AdvancedInstaller.com" /execute  ./ISSM.aip ./ISSM.aic
-
-#Get rid of temporary files: 
-cp ISSM-SetupFiles/ISSM.msi ./
-rm -rf ISSM.aip ISSM-SetupFiles ISSM.aic
Index: /issm/trunk/packagers/win7/package32.sh
===================================================================
--- /issm/trunk/packagers/win7/package32.sh	(revision 15396)
+++ /issm/trunk/packagers/win7/package32.sh	(revision 15396)
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+#get brand new project: 
+rm -rf ISSM.aip  ISSM-SetupFiles ISSM.msi
+cp ISSM.initial.aip ISSM.aip
+
+#get windows style path to files
+export ISSM_DIR_WIN=`cygpath -m "$ISSM_DIR"`
+
+#build list of files to put into the installer: 
+rm -rf ISSM.aic 
+cat << END > ISSM.aic
+;aic
+SetVersion "1.0"
+SetPackageName "ISSM.msi"
+END
+
+ls $ISSM_DIR_WIN/scripts/*.bat startup.m $ISSM_DIR_WIN/bin/*.h | awk '{printf("AddFile APPDIR %s\n",$1);}' | sed 's/\//\\/g' >> ISSM.aic
+
+cat << END >> ISSM.aic
+AddFolder PersonalFolder $ISSM_DIR_WIN\test
+AddFolder APPDIR $ISSM_DIR_WIN\bin
+NewEnvironment -name ISSM_TESTS -value [test_Dir]
+NewEnvironment -name ISSM_DIR -value [APPDIR]
+NewEnvironment -name ISSM_DIR_WIN -value [APPDIR]
+Save
+Rebuild
+END
+#Not needed anymore? 
+#DelEnvironment ISSM_TESTS
+#DelEnvironment ISSM_DIR
+#DelEnvironment ISSM_DIR_WIN
+
+#Run installer: 
+"C:/Program Files (x86)/Caphyon/Advanced Installer 10.1/bin/x86/AdvancedInstaller.com" /execute  ./ISSM.aip ./ISSM.aic
+
+#Get rid of temporary files: 
+cp ISSM-SetupFiles/ISSM.msi ./
+rm -rf ISSM.aip ISSM-SetupFiles ISSM.aic
Index: /issm/trunk/packagers/win7/package64.sh
===================================================================
--- /issm/trunk/packagers/win7/package64.sh	(revision 15396)
+++ /issm/trunk/packagers/win7/package64.sh	(revision 15396)
@@ -0,0 +1,48 @@
+#!/bin/bash
+
+#get brand new project: 
+rm -rf ISSM.aip  ISSM-SetupFiles ISSM.msi
+cp ISSM.initial.aip ISSM.aip
+
+#recover version: 
+version=`svn info | grep Revision | awk '{printf("%s\n",$2);}'`
+
+#get windows style path to files
+export ISSM_DIR_WIN=`cygpath -m "$ISSM_DIR"`
+
+#build list of files to put into the installer: 
+rm -rf ISSM.aic 
+cat << END > ISSM.aic
+;aic
+SetVersion "$version"
+SetPackageName "ISSM.msi"
+END
+
+ls $ISSM_DIR_WIN/scripts/*.bat startup.m $ISSM_DIR_WIN/bin/*.h | awk '{printf("AddFile APPDIR %s\n",$1);}' | sed 's/\//\\/g' >> ISSM.aic
+
+cat << END >> ISSM.aic
+AddFolder PersonalFolder $ISSM_DIR_WIN\test
+AddFolder PersonalFolder $ISSM_DIR_WIN\examples
+AddFolder APPDIR $ISSM_DIR_WIN\bin
+AddFolder APPDIR $ISSM_DIR_WIN\lib
+NewEnvironment -name ISSM_TESTS -value [test_Dir]
+NewEnvironment -name ISSM_DIR -value [APPDIR]
+NewEnvironment -name ISSM_DIR_WIN -value [APPDIR]
+Save
+Rebuild
+END
+#Not needed anymore? 
+#DelEnvironment ISSM_TESTS
+#DelEnvironment ISSM_DIR
+#DelEnvironment ISSM_DIR_WIN
+
+#Run installer: 
+"C:/Program Files (x86)/Caphyon/Advanced Installer 10.1/bin/x86/AdvancedInstaller.com" /execute  ./ISSM.aip ./ISSM.aic
+
+#Get rid of temporary files: 
+cp ISSM-SetupFiles/ISSM.msi ./
+rm -rf ISSM.aip ISSM-SetupFiles ISSM.aic
+
+#Upload?: 
+#scp ISSM.msi websites:/home/larour/files/ISSM64.msi
+#cp  ISSM.msi /cygrdive/z/Desktop/ISSM64.msi
Index: /issm/trunk/patches/Makefile.am_C
===================================================================
--- /issm/trunk/patches/Makefile.am_C	(revision 15396)
+++ /issm/trunk/patches/Makefile.am_C	(revision 15396)
@@ -0,0 +1,1018 @@
+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@
+
+EXEEXT=$(ISSMEXT)
+
+#Library declaration {{{
+lib_LIBRARIES = libISSMCore.a libISSMOverload.a
+
+if WRAPPERS
+lib_LIBRARIES += libISSMModules.a 
+endif
+#}}}
+
+#sources
+#Core sources{{{
+core_sources = ./main/issm.h\
+			   ./main/globals.h\
+			   ./datastructures/DataSet.h\
+					./datastructures/DataSet.cpp\
+					./datastructures/Object.h\
+					./datastructures/datastructures.h\
+					./classes/classes.h\
+					./classes/gauss/GaussTria.h\
+					./classes/gauss/GaussTria.cpp\
+					./classes/Update.h\
+					./classes/Element.h\
+					./classes/FemModel.h\
+					./classes/FemModel.cpp\
+					./classes/Material.h\
+					./classes/Load.h\
+					./classes/Contour.h\
+					./classes/Loads/Friction.h\
+					./classes/Loads/Friction.cpp\
+					./classes/Inputs/TransientInput.h\
+					./classes/Inputs/TransientInput.cpp\
+					./classes/Constraints/SpcTransient.cpp\
+					./classes/Constraints/SpcTransient.h\
+					./classes/IndependentObject.h\
+					./classes/IndependentObject.cpp\
+					./classes/DependentObject.h\
+					./classes/DependentObject.cpp\
+					./classes/DofIndexing.h\
+					./classes/DofIndexing.cpp\
+					./classes/IoModel.h\
+					./classes/IoModel.cpp\
+					./classes/Contours.h\
+					./classes/Contours.cpp\
+					./classes/Nodes.h\
+					./classes/Nodes.cpp\
+					./classes/Vertices.h\
+					./classes/Vertices.cpp\
+					./classes/Node.h\
+					./classes/Node.cpp\
+					./classes/Segment.h\
+					./classes/Vertex.h\
+					./classes/Vertex.cpp\
+					./classes/Hook.h\
+					./classes/Hook.cpp\
+					./classes/Patch.h\
+					./classes/Patch.cpp\
+					./classes/ElementResults/ElementResultLocal.h\
+					./classes/ElementResults/DoubleElementResult.h\
+					./classes/ElementResults/DoubleElementResult.cpp\
+					./classes/ElementResults/TriaP1ElementResult.h\
+					./classes/ElementResults/TriaP1ElementResult.cpp\
+					./classes/ElementResults/BoolElementResult.h\
+					./classes/ElementResults/BoolElementResult.cpp\
+					./classes/ExternalResults/Results.h\
+					./classes/ExternalResults/Results.cpp\
+					./classes/ExternalResults/ExternalResult.h\
+					./classes/ExternalResults/GenericExternalResult.h\
+					./classes/Elements/Elements.h\
+					./classes/Elements/Elements.cpp\
+					./classes/Elements/Tria.h\
+					./classes/Elements/Tria.cpp\
+					./classes/Elements/TriaHook.h\
+					./classes/Elements/TriaHook.cpp\
+					./classes/Elements/TriaRef.h\
+					./classes/Elements/TriaRef.cpp\
+					./classes/Inputs/Inputs.h\
+					./classes/Inputs/Inputs.cpp\
+					./classes/Inputs/Input.h\
+					./classes/Inputs/InputLocal.h\
+					./classes/Inputs/TriaP1Input.h\
+					./classes/Inputs/TriaP1Input.cpp\
+					./classes/Inputs/BoolInput.h\
+					./classes/Inputs/BoolInput.cpp\
+					./classes/Inputs/IntInput.h\
+					./classes/Inputs/IntInput.cpp\
+					./classes/Inputs/DoubleInput.h\
+					./classes/Inputs/DoubleInput.cpp\
+					./classes/Inputs/DatasetInput.h\
+					./classes/Inputs/DatasetInput.cpp\
+					./classes/Materials/Materials.h\
+					./classes/Materials/Materials.cpp\
+					./classes/Materials/Matice.h\
+					./classes/Materials/Matice.cpp\
+					./classes/Materials/Matdamageice.h\
+					./classes/Materials/Matdamageice.cpp\
+					./classes/Materials/Matpar.h\
+					./classes/Materials/Matpar.cpp\
+					./classes/Constraints/Constraints.h\
+					./classes/Constraints/Constraints.cpp\
+					./classes/Constraints/Constraint.h\
+					./classes/Constraints/SpcStatic.cpp\
+					./classes/Constraints/SpcStatic.h\
+					./classes/Constraints/SpcDynamic.cpp\
+					./classes/Constraints/SpcDynamic.h\
+					./classes/Loads/Loads.h\
+					./classes/Loads/Loads.cpp\
+					./classes/Loads/Penpair.cpp\
+					./classes/Loads/Penpair.h\
+					./classes/Loads/Pengrid.cpp\
+					./classes/Loads/Pengrid.h\
+					./classes/Loads/Icefront.cpp\
+					./classes/Loads/Icefront.h\
+					./classes/Loads/Numericalflux.cpp\
+					./classes/Loads/Numericalflux.h\
+					./classes/matrix/matrixobjects.h\
+					./classes/matrix/ElementMatrix.h\
+					./classes/matrix/ElementMatrix.cpp\
+					./classes/matrix/ElementVector.h\
+					./classes/matrix/ElementVector.cpp\
+					./classes/Params/Parameters.h\
+					./classes/Params/Parameters.cpp\
+					./classes/Params/Param.h\
+					./classes/Params/GenericParam.h\
+					./classes/Params/BoolParam.cpp\
+					./classes/Params/BoolParam.h\
+					./classes/Params/IntParam.cpp\
+					./classes/Params/IntParam.h\
+					./classes/Params/IntVecParam.cpp\
+					./classes/Params/IntVecParam.h\
+					./classes/Params/IntMatParam.cpp\
+					./classes/Params/IntMatParam.h\
+					./classes/Params/DoubleParam.cpp\
+					./classes/Params/DoubleParam.h\
+					./classes/Params/FileParam.cpp\
+					./classes/Params/FileParam.h\
+					./classes/Params/StringArrayParam.cpp\
+					./classes/Params/StringArrayParam.h\
+					./classes/Params/DoubleMatParam.cpp\
+					./classes/Params/DoubleMatParam.h\
+					./classes/Params/DoubleTransientMatParam.cpp\
+					./classes/Params/DoubleTransientMatParam.h\
+					./classes/Params/DoubleMatArrayParam.cpp\
+					./classes/Params/DoubleMatArrayParam.h\
+					./classes/Params/DoubleVecParam.cpp\
+					./classes/Params/DoubleVecParam.h\
+					./classes/Params/StringParam.cpp\
+					./classes/Params/StringParam.h\
+					./classes/Params/MatrixParam.h\
+					./classes/Params/MatrixParam.cpp\
+					./classes/Params/VectorParam.h\
+					./classes/Params/VectorParam.cpp\
+					./classes/Params/TransientParam.h\
+					./classes/Params/TransientParam.cpp\
+					./classes/Params/DataSetParam.h\
+					./classes/Params/DataSetParam.cpp\
+					./classes/Profiler.h\
+					./classes/Profiler.cpp\
+					./shared/shared.h\
+					./shared/MemOps/MemOps.h\
+					./shared/Matrix/matrix.h\
+					./shared/Matrix/MatrixUtils.cpp\
+					./shared/io/io.h\
+					./shared/io/Disk/diskio.h\
+					./shared/io/Disk/pfopen.cpp\
+					./shared/io/Disk/pfclose.cpp\
+					./shared/io/Disk/WriteLockFile.cpp\
+					./shared/io/Print/PrintfFunction.cpp\
+					./shared/io/Print/Print.h\
+					./shared/io/Comm/Comm.h\
+					./shared/io/Comm/CommDef.h\
+					./shared/io/Comm/IssmComm.h\
+					./shared/io/Comm/IssmComm.cpp\
+					./shared/LatLong/Ll2xyx.cpp\
+					./shared/LatLong/Xy2llx.cpp\
+					./shared/Enum/Enum.h\
+					./shared/Enum/EnumDefinitions.h\
+					./shared/Enum/EnumToStringx.cpp\
+					./shared/Enum/StringToEnumx.cpp\
+					./shared/Numerics/numerics.h\
+					./shared/Numerics/types.h\
+					./shared/Numerics/constants.h\
+					./shared/Numerics/Verbosity.h\
+					./shared/Numerics/Verbosity.cpp\
+					./shared/Numerics/GaussPoints.h\
+					./shared/Numerics/GaussPoints.cpp\
+					./shared/Numerics/cross.cpp\
+					./shared/Numerics/isnan.h\
+					./shared/Numerics/isnan.cpp\
+					./shared/Numerics/cubic.cpp\
+					./shared/Numerics/extrema.cpp\
+					./shared/Numerics/XZvectorsToCoordinateSystem.cpp\
+					./shared/Numerics/UnitConversion.cpp\
+					./shared/Numerics/OptArgs.h\
+					./shared/Numerics/OptPars.h\
+					./shared/Exceptions/exceptions.h\
+					./shared/Exceptions/Exceptions.cpp\
+					./shared/Exceptions/exprintf.cpp\
+					./shared/Sorting/binary_search.cpp\
+					./shared/Sorting/sorting.h\
+					./shared/Elements/elements.h\
+					./shared/Elements/Paterson.cpp\
+					./shared/Elements/Arrhenius.cpp\
+					./shared/Elements/PrintArrays.cpp\
+					./shared/Elements/PddSurfaceMassBalance.cpp\
+					./shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp\
+					./shared/String/sharedstring.h\
+					./shared/String/DescriptorIndex.cpp\
+					./toolkits/metis/metisincludes.h\
+					./toolkits/issm/issmtoolkit.h\
+					./toolkits/issm/IssmToolkitUtils.h\
+					./toolkits/issm/IssmToolkitUtils.cpp\
+					./toolkits/issm/IssmAbsMat.h\
+					./toolkits/issm/IssmAbsVec.h\
+					./toolkits/issm/IssmDenseMat.h\
+					./toolkits/issm/IssmMat.h\
+					./toolkits/issm/IssmSeqVec.h\
+					./toolkits/issm/IssmVec.h\
+					./toolkits/issm/IssmSolver.h\
+					./toolkits/issm/IssmSolver.cpp\
+					./toolkits/issm/Bucket.h\
+					./toolkits/adolc/adolcincludes.h\
+					./toolkits/adolc/AdolcEdf.h\
+					./toolkits/ToolkitOptions.h\
+					./toolkits/ToolkitOptions.cpp\
+					./toolkits/triangle/triangleincludes.h\
+					./toolkits/objects/toolkitobjects.h\
+					./toolkits/objects/Matrix.h\
+					./toolkits/objects/Vector.h\
+					./toolkits/objects/Solver.h\
+					./toolkitsenums.h\
+					./toolkits.h\
+					./modules/ModelProcessorx/ModelProcessorx.h\
+					./modules/ModelProcessorx/ModelProcessorx.cpp\
+					./modules/ModelProcessorx/DistributeNumDofs.cpp\
+					./modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp\
+					./modules/ModelProcessorx/NodesPartitioning.cpp\
+					./modules/ModelProcessorx/SortDataSets.cpp\
+					./modules/ModelProcessorx/UpdateCounters.cpp\
+					./modules/ModelProcessorx/CreateDataSets.cpp\
+					./modules/ModelProcessorx/CreateParameters.cpp\
+					./modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp\
+					./modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp\
+					./modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp\
+					./modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp\
+					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h\
+					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp\
+					./modules/NodesDofx/NodesDofx.h\
+					./modules/NodesDofx/NodesDofx.cpp\
+					./modules/NodalValuex/NodalValuex.h\
+					./modules/NodalValuex/NodalValuex.cpp\
+					./modules/VerticesDofx/VerticesDofx.h\
+					./modules/VerticesDofx/VerticesDofx.cpp\
+					./modules/VertexCoordinatesx/VertexCoordinatesx.h\
+					./modules/VertexCoordinatesx/VertexCoordinatesx.cpp\
+					./modules/OutputResultsx/OutputResultsx.h\
+					./modules/OutputResultsx/OutputResultsx.cpp\
+					./modules/InputDuplicatex/InputDuplicatex.h\
+					./modules/InputDuplicatex/InputDuplicatex.cpp\
+					./modules/InputScalex/InputScalex.h\
+					./modules/InputScalex/InputScalex.cpp\
+					./modules/SurfaceAreax/SurfaceAreax.h\
+					./modules/SurfaceAreax/SurfaceAreax.cpp\
+					./modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h\
+					./modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp\
+					./modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h\
+					./modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp\
+					./modules/IoModelToConstraintsx/IoModelToConstraintsx.h\
+					./modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp\
+					./modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h\
+					./modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp\
+					./modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h\
+					./modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp\
+					./modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h\
+					./modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp\
+					./modules/GetVectorFromInputsx/GetVectorFromInputsx.h\
+					./modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp\
+					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h\
+					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp\
+					./modules/InputArtificialNoisex/InputArtificialNoisex.h\
+					./modules/InputArtificialNoisex/InputArtificialNoisex.cpp\
+					./modules/ConfigureObjectsx/ConfigureObjectsx.h\
+					./modules/ConfigureObjectsx/ConfigureObjectsx.cpp\
+					./modules/ComputeBasalStressx/ComputeBasalStressx.h\
+					./modules/ComputeBasalStressx/ComputeBasalStressx.cpp\
+					./modules/ComputeStrainRatex/ComputeStrainRatex.h\
+					./modules/ComputeStrainRatex/ComputeStrainRatex.cpp\
+					./modules/SpcNodesx/SpcNodesx.h\
+					./modules/SpcNodesx/SpcNodesx.cpp\
+					./modules/PositiveDegreeDayx/PositiveDegreeDayx.h\
+					./modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp\
+					./modules/Delta18oParameterizationx/Delta18oParameterizationx.h\
+					./modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp\
+					./modules/SmbGradientsx/SmbGradientsx.h\
+					./modules/SmbGradientsx/SmbGradientsx.cpp\
+					./modules/MeshPartitionx/MeshPartitionx.h\
+					./modules/Reducevectorgtofx/Reducevectorgtofx.cpp\
+					./modules/Reducevectorgtofx/Reducevectorgtofx.h\
+					./modules/Reduceloadx/Reduceloadx.h\
+					./modules/Reduceloadx/Reduceloadx.cpp\
+					./modules/ConstraintsStatex/ConstraintsStatex.cpp\
+					./modules/ConstraintsStatex/ConstraintsStatex.h\
+					./modules/ConstraintsStatex/ConstraintsStateLocal.h\
+					./modules/ResetConstraintsx/ResetConstraintsx.h\
+					./modules/ResetConstraintsx/ResetConstraintsx.cpp\
+					./modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h\
+					./modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp\
+					./modules/Solverx/Solverx.cpp\
+					./modules/Solverx/Solverx.h\
+					./modules/VecMergex/VecMergex.cpp\
+					./modules/VecMergex/VecMergex.h\
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp\
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h\
+					./modules/InputToResultx/InputToResultx.cpp\
+					./modules/InputToResultx/InputToResultx.h\
+					./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.h\
+					./classes/Options/Options.cpp\
+					./classes/Options/Option.h\
+					./classes/Options/GenericOption.h\
+					./classes/Options/OptionUtilities.cpp\
+					./classes/Options/OptionUtilities.h\
+					./classes/RiftStruct.cpp\
+					./classes/RiftStruct.h
+#}}}
+#DAKOTA sources  {{{
+dakota_sources = ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
+					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
+					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h\
+					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp\
+					  ./modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h\
+					  ./modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
+					  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
+					  ./analyses/dakota_core.cpp\
+					  ./analyses/DakotaSpawnCore.h\
+					  ./analyses/DakotaSpawnCore.cpp
+#}}}
+#Transient sources  {{{
+transient_sources  = ./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp \
+							./analyses/transient_core.cpp
+#}}}
+#Steadystate sources  {{{
+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
+#}}}
+#Thermal sources  {{{
+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  {{{
+control_sources= ./modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp\
+					  ./modules/ControlInputGetGradientx/ControlInputGetGradientx.h\
+					  ./modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp\
+					  ./modules/ControlInputSetGradientx/ControlInputSetGradientx.h\
+					  ./modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp\
+					  ./modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h\
+					  ./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp\
+					  ./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h\
+					  ./modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp\
+					  ./modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h\
+					  ./modules/ModelProcessorx/Control/CreateParametersControl.cpp\
+					  ./modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp\
+					  ./modules/InputControlUpdatex/InputControlUpdatex.h\
+					  ./modules/InputControlUpdatex/InputControlUpdatex.cpp\
+					  ./modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h\
+					  ./modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp\
+					  ./modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h\
+					  ./modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp\
+					  ./modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h\
+					  ./modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp\
+					  ./modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h\
+					  ./modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp\
+					  ./modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h\
+					  ./modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp\
+					  ./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h\
+					  ./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp\
+					  ./modules/Orthx/Orthx.h\
+					  ./modules/Orthx/Orthx.cpp\
+					  ./modules/Gradjx/Gradjx.h\
+					  ./modules/Gradjx/Gradjx.cpp\
+					  ./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp\
+					  ./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h\
+					  ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp\
+					  ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h\
+					  ./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp\
+					  ./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h\
+					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp\
+					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h\
+					  ./classes/Inputs/ControlInput.h\
+					  ./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  {{{
+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  {{{
+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  {{{
+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  {{{
+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  {{{
+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/GiaDeflectionCorex.h\
+					./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\
+					./classes/GiaDeflectionCoreArgs.h
+
+#}}}
+#Groundingline sources  {{{
+groundingline_sources= ./modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp\
+					        ./modules/GroundinglineMigrationx/GroundinglineMigrationx.h
+#}}}
+#Rifts sources  {{{
+rifts_sources = ./classes/Loads/Riftfront.cpp\
+				    ./classes/Loads/Riftfront.h\
+				    ./modules/ConstraintsStatex/RiftConstraintsState.cpp
+#}}}
+#Android sources  {{{
+android_sources = 
+#}}}
+#3D sources  {{{
+threed_sources = ./classes/gauss/GaussPenta.h\
+				     ./classes/gauss/GaussPenta.cpp\
+				     ./classes/ElementResults/PentaP1ElementResult.h\
+				     ./classes/ElementResults/PentaP1ElementResult.cpp\
+				     ./classes/Inputs/PentaP1Input.h\
+				     ./classes/Inputs/PentaP1Input.cpp\
+				     ./classes/Elements/Penta.h\
+				     ./classes/Elements/Penta.cpp\
+				     ./classes/Elements/PentaHook.h\
+				     ./classes/Elements/PentaHook.cpp\
+				     ./classes/Elements/PentaRef.h\
+				     ./classes/Elements/PentaRef.cpp
+#}}}
+#Bamg sources  {{{
+bamg_sources =  ./bamg/bamgobjects.h\
+				./bamg/BamgGeom.h\
+				./bamg/BamgGeom.cpp\
+				./bamg/BamgMesh.h\
+				./bamg/BamgMesh.cpp\
+				./bamg/BamgOpts.h\
+				./bamg/BamgOpts.cpp\
+				./bamg/CrackedEdge.h\
+				./bamg/CrackedEdge.cpp\
+				./bamg/Curve.h\
+				./bamg/Curve.cpp\
+				./bamg/Direction.h\
+				./bamg/Direction.cpp\
+				./bamg/DoubleAndInt.h\
+				./bamg/Edge.h\
+				./bamg/Edge.cpp\
+				./bamg/GeomEdge.h\
+				./bamg/GeomEdge.cpp\
+				./bamg/GeomSubDomain.h\
+				./bamg/GeomSubDomain.cpp\
+				./bamg/GeomVertex.h\
+				./bamg/GeomVertex.cpp\
+				./bamg/Geometry.cpp\
+				./bamg/Geometry.h\
+				./bamg/ListofIntersectionTriangles.cpp\
+				./bamg/ListofIntersectionTriangles.h\
+				./bamg/EigenMetric.cpp\
+				./bamg/Metric.cpp\
+				./bamg/Metric.h\
+				./bamg/BamgQuadtree.cpp\
+				./bamg/BamgQuadtree.h\
+				./bamg/R2.h\
+				./bamg/SetOfE4.cpp\
+				./bamg/SetOfE4.h\
+				./bamg/SubDomain.h\
+				./bamg/SubDomain.cpp\
+				./bamg/AdjacentTriangle.h\
+				./bamg/AdjacentTriangle.cpp\
+				./bamg/Triangle.cpp\
+				./bamg/det.h \
+				./bamg/Triangle.h\
+				./bamg/BamgVertex.cpp\
+				./bamg/BamgVertex.h\
+				./bamg/VertexOnEdge.h\
+				./bamg/VertexOnEdge.cpp\
+				./bamg/VertexOnGeom.h\
+				./bamg/VertexOnGeom.cpp\
+				./bamg/VertexOnVertex.h\
+				./bamg/VertexOnVertex.cpp\
+				./bamg/Mesh.cpp\
+				./bamg/Mesh.h\
+				./shared/Bamg/Abs.h \
+				./shared/Bamg/BigPrimeNumber.h\
+				./shared/Bamg/BigPrimeNumber.cpp\
+				./shared/Bamg/BinaryRand.h \
+				./shared/Bamg/Exchange.h \
+				./shared/Bamg/extrema.h \
+				./shared/Bamg/HeapSort.h \
+				./shared/Bamg/OppositeAngle.h \
+				./modules/Bamgx/Bamgx.cpp\
+				./modules/Bamgx/Bamgx.h\
+				./modules/BamgConvertMeshx/BamgConvertMeshx.cpp\
+				./modules/BamgConvertMeshx/BamgConvertMeshx.h\
+				./modules/BamgTriangulatex/BamgTriangulatex.cpp\
+				./modules/BamgTriangulatex/BamgTriangulatex.h
+#}}}
+#Kriging sources  {{{
+kriging_sources = ./classes/kriging/Observations.h\
+						./classes/kriging/Observations.cpp\
+						./classes/kriging/Variogram.h \
+						./classes/kriging/GaussianVariogram.h\
+						./classes/kriging/GaussianVariogram.cpp\
+						./classes/kriging/ExponentialVariogram.h\
+						./classes/kriging/ExponentialVariogram.cpp\
+						./classes/kriging/SphericalVariogram.h\
+						./classes/kriging/SphericalVariogram.cpp\
+						./classes/kriging/PowerVariogram.h\
+						./classes/kriging/PowerVariogram.cpp\
+						./classes/kriging/Quadtree.h\
+						./classes/kriging/Quadtree.cpp\
+						./classes/kriging/Observation.h\
+						./classes/kriging/Observation.cpp\
+						./modules/Krigingx/Krigingx.cpp\
+						./modules/Krigingx/Krigingx.h
+
+#For parallel kriging, only difference is ./modules/Krigingx/pKrigingx.cpp with no multithreading
+pkriging_sources = ./classes/kriging/Observations.h\
+						./classes/kriging/Observations.cpp\
+						./classes/kriging/Variogram.h \
+						./classes/kriging/GaussianVariogram.h\
+						./classes/kriging/GaussianVariogram.cpp\
+						./classes/kriging/ExponentialVariogram.h\
+						./classes/kriging/ExponentialVariogram.cpp\
+						./classes/kriging/SphericalVariogram.h\
+						./classes/kriging/SphericalVariogram.cpp\
+						./classes/kriging/PowerVariogram.h\
+						./classes/kriging/PowerVariogram.cpp\
+						./classes/kriging/Quadtree.h\
+						./classes/kriging/Quadtree.cpp\
+						./classes/kriging/Observation.h\
+						./classes/kriging/Observation.cpp\
+						./modules/Krigingx/pKrigingx.cpp\
+						./modules/Krigingx/Krigingx.h
+
+#}}}
+#Kml sources  {{{
+kml_sources = ./modules/Exp2Kmlx/Exp2Kmlx.h\
+			     ./modules/Exp2Kmlx/Exp2Kmlx.cpp\
+			     ./modules/Kml2Expx/Kml2Expx.h\
+			     ./modules/Kml2Expx/Kml2Expx.cpp\
+			     ./modules/Shp2Expx/Shp2Expx.h\
+			     ./modules/Shp2Expx/Shp2Expx.cpp\
+			     ./modules/Shp2Kmlx/Shp2Kmlx.h\
+			     ./modules/Shp2Kmlx/Shp2Kmlx.cpp\
+			     ./modules/KMLFileReadx/KMLFileReadx.h\
+			     ./modules/KMLFileReadx/KMLFileReadx.cpp\
+			     ./modules/KMLMeshWritex/KMLMeshWritex.h\
+			     ./modules/KMLMeshWritex/KMLMeshWritex.cpp\
+			     ./modules/KMLOverlayx/KMLOverlayx.h\
+			     ./modules/KMLOverlayx/KMLOverlayx.cpp\
+			     ./kml/kmlobjects.h\
+			     ./kml/KML_Attribute.cpp\
+			     ./kml/KML_Attribute.h\
+			     ./kml/KML_Comment.cpp\
+			     ./kml/KML_Comment.h\
+			     ./kml/KML_ColorStyle.cpp\
+			     ./kml/KML_ColorStyle.h\
+			     ./kml/KML_Container.cpp\
+			     ./kml/KML_Container.h\
+			     ./kml/KML_Document.cpp\
+			     ./kml/KML_Document.h\
+			     ./kml/KML_Feature.cpp\
+			     ./kml/KML_Feature.h\
+			     ./kml/KML_File.cpp\
+			     ./kml/KML_File.h\
+			     ./kml/KML_Folder.cpp\
+			     ./kml/KML_Folder.h\
+			     ./kml/KML_Geometry.cpp\
+			     ./kml/KML_Geometry.h\
+			     ./kml/KML_GroundOverlay.cpp\
+			     ./kml/KML_GroundOverlay.h\
+			     ./kml/KML_Icon.cpp\
+			     ./kml/KML_Icon.h\
+			     ./kml/KML_LatLonBox.cpp\
+		  	     ./kml/KML_LatLonBox.h\
+			     ./kml/KML_LinearRing.cpp\
+			     ./kml/KML_LinearRing.h\
+			     ./kml/KML_LineString.cpp\
+			     ./kml/KML_LineString.h\
+			     ./kml/KML_LineStyle.cpp\
+			     ./kml/KML_LineStyle.h\
+			     ./kml/KML_MultiGeometry.cpp\
+			     ./kml/KML_MultiGeometry.h\
+			     ./kml/KML_Object.cpp\
+			     ./kml/KML_Object.h\
+			     ./kml/KML_Overlay.cpp\
+			     ./kml/KML_Overlay.h\
+			     ./kml/KML_Point.cpp\
+			     ./kml/KML_Point.h\
+			     ./kml/KML_Placemark.cpp\
+			     ./kml/KML_Placemark.h\
+			     ./kml/KML_Polygon.cpp\
+			     ./kml/KML_Polygon.h\
+			     ./kml/KML_PolyStyle.cpp\
+			     ./kml/KML_PolyStyle.h\
+			     ./kml/KML_Style.cpp\
+			     ./kml/KML_Style.h\
+			     ./kml/KML_StyleSelector.cpp\
+			     ./kml/KML_StyleSelector.h\
+			     ./kml/KML_SubStyle.cpp\
+			     ./kml/KML_SubStyle.h\
+			     ./kml/KML_Unknown.cpp\
+			     ./kml/KML_Unknown.h\
+			     ./kml/KMLFileReadUtils.cpp\
+			     ./kml/KMLFileReadUtils.h
+#}}}
+#Petsc sources  {{{
+petsc_sources= ./toolkits/petsc\
+					./toolkits/petsc/patches\
+					./toolkits/petsc/patches/SolverEnum.h\
+					./toolkits/petsc/patches/petscpatches.h\
+					./toolkits/petsc/patches/VecToMPISerial.cpp\
+					./toolkits/petsc/patches/MatToSerial.cpp\
+					./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/petscobjects.h\
+					./toolkits/petsc/objects/PetscMat.h\
+					./toolkits/petsc/objects/PetscMat.cpp\
+					./toolkits/petsc/objects/PetscVec.h\
+					./toolkits/petsc/objects/PetscVec.cpp\
+					./toolkits/petsc/objects/PetscSolver.cpp\
+					./toolkits/petsc/objects/PetscSolver.h\
+					./toolkits/petsc/petscincludes.h
+
+#}}}
+#Mumps sources  {{{
+mumps_sources=      ./toolkits/mumps\
+					./toolkits/mumps/mumpsincludes.h\
+					./toolkits/mumps/MpiDenseMumpsSolve.cpp
+#}}}
+#Gsl sources  {{{
+gsl_sources=      ./toolkits/gsl\
+					./toolkits/gsl/gslincludes.h\
+					./toolkits/gsl/DenseGslSolve.cpp
+#}}}
+#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\
+				./toolkits/issm/IssmMpiVec.h
+#}}}
+#Metis sources  {{{
+metis_sources= ./toolkits/metis/patches/metispatches.h\
+					./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
+#}}}
+#Modules sources{{{
+modules_sources= ./shared/Threads/issm_threads.h\
+			./shared/Threads/LaunchThread.cpp\
+			./shared/Threads/PartitionRange.cpp\
+			./shared/Exp/exp.h\
+			./shared/Exp/exp.cpp\
+			./shared/TriMesh/trimesh.h\
+			./shared/TriMesh/AssociateSegmentToElement.cpp\
+			./shared/TriMesh/GridInsideHole.cpp\
+			./shared/TriMesh/OrderSegments.cpp\
+			./shared/TriMesh/SplitMeshForRifts.cpp\
+			./shared/TriMesh/TriMeshUtils.cpp\
+			./modules/Chacox/Chacox.h\
+			./modules/Chacox/Chacox.cpp\
+			./modules/Chacox/input_parse.cpp\
+			./modules/Chacox/chaco_seconds.cpp\
+			./modules/Chacox/user_params.cpp\
+			./modules/TriaSearchx/TriaSearchx.h\
+			./modules/TriaSearchx/TriaSearchx.cpp\
+			./modules/TriMeshx/TriMeshx.h\
+			./modules/TriMeshx/TriMeshx.cpp\
+			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h\
+			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp\
+			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp\
+			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h\
+			./modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp\
+			./modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp\
+			./modules/InterpFromMesh2dx/InterpFromMesh2dx.h\
+			./modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp\
+			./modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h\
+			./modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp\
+			./modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h\
+			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp\
+			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h\
+			./modules/HoleFillerx/HoleFillerx.cpp\
+			./modules/HoleFillerx/HoleFillerx.h\
+			./modules/EdgeDetectionx/EdgeDetectionx.cpp\
+			./modules/EdgeDetectionx/EdgeDetectionx.h\
+			./modules/AverageFilterx/AverageFilterx.cpp\
+			./modules/AverageFilterx/AverageFilterx.h\
+			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp\
+			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h\
+			./modules/ContourToMeshx/ContourToMeshx.cpp\
+			./modules/ContourToMeshx/ContourToMeshxt.cpp\
+			./modules/ContourToMeshx/ContourToMeshx.h\
+			./modules/ContourToNodesx/ContourToNodesx.cpp\
+			./modules/ContourToNodesx/ContourToNodesx.h\
+			./modules/Reducevectorgtosx/Reducevectorgtosx.cpp\
+			./modules/Reducevectorgtosx/Reducevectorgtosx.h\
+			./modules/NodeConnectivityx/NodeConnectivityx.cpp\
+			./modules/NodeConnectivityx/NodeConnectivityx.h\
+			./modules/ElementConnectivityx/ElementConnectivityx.cpp\
+			./modules/ElementConnectivityx/ElementConnectivityx.h\
+			./modules/Scotchx/Scotchx.cpp\
+			./modules/Scotchx/Scotchx.h\
+			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp\
+			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h
+#}}}
+
+#{{{ Conditional build-up of sources
+#ISSM sources are a combination of core sources and sources related to specific capabilities (which can 
+#be activated by autotools conditionals 
+
+#First the core
+issm_sources  =  $(core_sources)
+
+#Now the optional source
+if DAKOTA
+issm_sources  +=  $(dakota_sources)
+endif
+
+if PETSC
+issm_sources  +=  $(petsc_sources)
+endif
+
+if MUMPS
+issm_sources  +=  $(mumps_sources)
+endif
+
+if GSL
+issm_sources  +=  $(gsl_sources)
+endif
+
+if TRANSIENT
+issm_sources  +=  $(transient_sources)
+endif
+
+if STEADYSTATE
+issm_sources  +=  $(steadystate_sources)
+endif
+
+if PROGNOSTIC
+issm_sources  +=  $(prognostic_sources)
+endif
+
+if THERMAL
+issm_sources  +=  $(thermal_sources)
+endif
+
+if GIA
+issm_sources  +=  $(gia_sources)
+endif
+
+if CONTROL
+issm_sources  +=  $(control_sources)
+endif
+
+if HYDROLOGY
+issm_sources  +=  $(hydrology_sources)
+endif
+
+if DIAGNOSTIC
+issm_sources  +=  $(diagnostic_sources)
+endif
+
+if BALANCED
+issm_sources  +=  $(balanced_sources)
+endif
+
+if SLOPE
+issm_sources  +=  $(slope_sources)
+endif
+
+if GROUNDINGLINE
+issm_sources +=  $(groundingline_sources)
+endif
+
+if RIFTS
+issm_sources +=  $(rifts_sources)
+endif
+
+if ANDROID
+issm_sources +=  $(android_sources)
+endif
+
+if THREED
+issm_sources +=  $(threed_sources)
+endif
+
+if MPI
+issm_sources +=  $(mpi_sources)
+endif
+
+if METIS
+issm_sources +=  $(metis_sources)
+endif
+
+if KRIGING
+issm_sources +=  $(pkriging_sources)
+endif
+#}}}
+#Library flags and sources {{{
+ALLCXXFLAGS= -fPIC -D_GNU_SOURCE -fno-omit-frame-pointer -pthread -D_CPP_  $(CXXFLAGS) $(CXXOPTFLAGS) 
+
+libISSMCore_a_SOURCES  = $(issm_sources)
+libISSMCore_a_CXXFLAGS = $(ALLCXXFLAGS)
+libISSMCore_a_FFLAGS = $(AM_FFLAGS)
+
+if WRAPPERS
+libISSMModules_a_SOURCES = $(modules_sources)
+libISSMModules_a_SOURCES += $(bamg_sources)
+if KRIGING
+libISSMModules_a_SOURCES += $(kriging_sources)
+endif
+if KML
+libISSMModules_a_SOURCES += $(kml_sources)
+endif
+libISSMModules_a_CXXFLAGS = $(ALLCXXFLAGS)
+libISSMModules_a_LIBADD = ./libISSMCore.a
+endif
+
+if VERSION
+AM_LDFLAGS =
+else
+AM_LDFLAGS = -avoid-version
+endif
+#}}}
+#Overload library, to overload any non-standard symbols. {{{
+libISSMOverload_a_SOURCES = ./shared/String/stricmp.c
+libISSMOverload_a_CFLAGS  = -fPIC -D_C_ $(COPTFLAGS) $(CFLAGS)
+#}}}
+
+#Executable {{{
+if ANDROID
+if ANDROIDEXE
+bin_PROGRAMS = issm 
+else
+bin_PROGRAMS = 
+endif
+else
+bin_PROGRAMS = issm 
+endif
+
+#Standard libraries
+LDADD = ./libISSMCore.a ./libISSMOverload.a
+
+#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)
+
+if FORTRAN
+LDADD += $(FLIBS)
+endif
+
+issm_SOURCES = main/issm.cpp
+issm_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
+
+if KRIGING
+bin_PROGRAMS += kriging
+kriging_SOURCES = main/kriging.cpp
+kriging_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
+endif
+#}}}
+#Automatic differentiation: append this fold to the end of the src/c/Makefile.am to get this Makefile.am {{{
+if ADIC2 
+lib_LIBRARIES += libAD.a libISSMRose.a
+
+#ADIC2 library, for automatic differentiation 
+#libAD_a_SOURCES = ./mini1.ad.c
+libAD_a_SOURCES = 
+libAD_a_CFLAGS = -fPIC -D_C_ $(COPTFLAGS)
+
+
+#test rose preprocessing 
+%.r2cpp.cpp : %.cpp
+	testTranslator -rose:o $@ -rose:skipfinalCompileStep -DHAVE_CONFIG_H -D_C_ -I. -I../.. $(INCLUDES) $<
+libISSMRose_a_SOURCES = $(libISSMCore_a_SOURCES:.cpp=.r2cpp.cpp)
+libISSMRose_a_CXXFLAGS= -fPIC -D_C_ $(CXXOPTFLAGS)
+
+
+
+#Automatic differentiation rules: 
+%.ad.c: %.c
+	adic2 -mforward  $< --nary
+
+
+
+#Executable
+bin_PROGRAMS +=  issmRose.exe
+issmRose_exe_LDADD = ./libISSMRose.a $(LDADD)
+issmRose_exe_SOURCES = main/issm.cpp
+issmRose_exe_CXXFLAGS= -fPIC $(CXXOPTFLAGS) $(COPTFLAGS) 
+LDADD +=  $(ADIC2LIB) 
+
+endif #}}}
Index: /issm/trunk/patches/Makefile.am_MATLAB
===================================================================
--- /issm/trunk/patches/Makefile.am_MATLAB	(revision 15396)
+++ /issm/trunk/patches/Makefile.am_MATLAB	(revision 15396)
@@ -0,0 +1,267 @@
+AM_CPPFLAGS = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@
+
+lib_LIBRARIES = libISSMMatlab.a 
+
+EXEEXT=$(MATLABWRAPPEREXT)
+
+#matlab io{{{
+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
+
+ALLCXXFLAGS = /D_GNU_SOURCE /D_CPP_ /D_WRAPPERS_ $(CXXFLAGS) $(CXXOPTFLAGS) 
+libISSMMatlab_a_SOURCES = $(io_sources)
+libISSMMatlab_a_CXXFLAGS = $(ALLCXXFLAGS)
+
+#}}}
+#Wrappers {{{
+if WRAPPERS
+bin_PROGRAMS =  AverageFilter\
+						 BamgMesher\
+						 BamgConvertMesh\
+						 BamgTriangulate\
+						 ContourToMesh\
+						 ContourToNodes\
+						 EdgeDetection\
+						 ElementConnectivity\
+						 EnumToString\
+						 ExpSimplify\
+						 HoleFiller\
+						 InternalFront\
+						 InterpFromGridToMesh\
+						 InterpFromMeshToMesh2d\
+						 InterpFromMeshToMesh3d\
+						 InterpFromMeshToGrid\
+						 InterpFromMesh2d\
+						 Ll2xy\
+						 NodeConnectivity\
+						 MeshPartition\
+						 MeshProfileIntersection\
+						 PointCloudFindNeighbors\
+						 PropagateFlagsFromConnectivity\
+						 StringToEnum\
+						 TriaSearch\
+						 TriMesh\
+						 TriMeshProcessRifts\
+						 Scotch\
+						 Xy2ll\
+						 Chaco
+
+if KRIGING
+bin_PROGRAMS +=  Kriging
+endif
+if KML
+bin_PROGRAMS +=  KMLFileRead\
+				   KMLMeshWrite\
+				   KMLOverlay\
+				   Exp2Kml\
+				   Kml2Exp\
+				   Shp2Exp\
+				   Shp2Kml
+endif
+endif
+#}}}
+#Flags and libraries {{{
+#if SHAREDLIBS
+#deps = ../../c/libISSMCore ../../c/libISSMModules.la
+#else
+#deps = ../../c/libISSMCore.a ../../c/libISSMModules.a
+#endif
+#deps +=  $(MATHLIB)
+deps =  $(MATHLIB)
+
+#Triangle library
+AM_CXXFLAGS =  /DTRILIBRARY /DANSI_DECLARATORS /DNO_TIMER
+
+#Matlab part
+AM_LDFLAGS = 
+if VERSION
+AM_LDFLAGS +=
+else
+AM_LDFLAGS += -avoid-version
+endif
+deps += ./libISSMMatlab.a
+AM_LDFLAGS += --no-warnings 
+
+AM_CXXFLAGS +=  /D_HAVE_MATLAB_MODULES_  /D_GNU_SOURCE 
+
+deps += ../../c/libISSMModules.a ../../c/libISSMCore.a  
+if ADOLC
+deps += $(ADOLCLIB)
+endif
+
+#MEXLIB needs to be the last (undefined references on larsen)
+deps += ${MEXLIB}
+
+#Optimization flags:
+AM_CXXFLAGS += $(CXXOPTFLAGS) 
+#}}}
+#Bin sources {{{
+AverageFilter_SOURCES = ../AverageFilter/AverageFilter.cpp\
+									../AverageFilter/AverageFilter.h
+AverageFilter_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+BamgMesher_SOURCES = ../BamgMesher/BamgMesher.cpp\
+								../BamgMesher/BamgMesher.h
+BamgMesher_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+BamgConvertMesh_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
+									  ../BamgConvertMesh/BamgConvertMesh.h
+BamgConvertMesh_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+BamgTriangulate_SOURCES = ../BamgTriangulate/BamgTriangulate.cpp\
+									  ../BamgTriangulate/BamgTriangulate.h
+BamgTriangulate_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Chaco_SOURCES = ../Chaco/Chaco.cpp\
+						 ../Chaco/Chaco.h
+Chaco_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(CHACOLIB) $(GSLLIB)
+
+ContourToMesh_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
+									../ContourToMesh/ContourToMesh.h
+ContourToMesh_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+ContourToNodes_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
+									 ../ContourToNodes/ContourToNodes.h
+ContourToNodes_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+ElementConnectivity_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
+											../ElementConnectivity/ElementConnectivity.h
+ElementConnectivity_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+EnumToString_SOURCES = ../EnumToString/EnumToString.cpp\
+								  ../EnumToString/EnumToString.h
+EnumToString_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+StringToEnum_SOURCES = ../StringToEnum/StringToEnum.cpp\
+								  ../StringToEnum/StringToEnum.h
+StringToEnum_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+HoleFiller_SOURCES = ../HoleFiller/HoleFiller.cpp\
+								../HoleFiller/HoleFiller.h
+HoleFiller_LDADD = ${deps} $(MPILIB) $(PETSCLIB)  $(GSLLIB)
+
+InternalFront_SOURCES = ../InternalFront/InternalFront.cpp\
+									../InternalFront/InternalFront.h
+InternalFront_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+InterpFromGridToMesh_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
+											 ../InterpFromGridToMesh/InterpFromGridToMesh.h
+InterpFromGridToMesh_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+InterpFromMeshToMesh2d_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
+												../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
+InterpFromMeshToMesh2d_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+InterpFromMeshToMesh3d_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
+												../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
+InterpFromMeshToMesh3d_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+InterpFromMeshToGrid_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
+											 ../InterpFromMeshToGrid/InterpFromMeshToGrid.h
+InterpFromMeshToGrid_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+InterpFromMesh2d_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp\
+										../InterpFromMesh2d/InterpFromMesh2d.h
+InterpFromMesh2d_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+KMLFileRead_SOURCES = ../KMLFileRead/KMLFileRead.cpp\
+								 ../KMLFileRead/KMLFileRead.h
+KMLFileRead_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+KMLMeshWrite_SOURCES = ../KMLMeshWrite/KMLMeshWrite.cpp\
+								  ../KMLMeshWrite/KMLMeshWrite.h
+KMLMeshWrite_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+KMLOverlay_SOURCES = ../KMLOverlay/KMLOverlay.cpp\
+								../KMLOverlay/KMLOverlay.h
+KMLOverlay_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Xy2ll_SOURCES = ../Xy2ll/Xy2ll.cpp\
+						 ../Xy2ll/Xy2ll.h
+Xy2ll_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Ll2xy_SOURCES = ../Ll2xy/Ll2xy.cpp\
+						 ../Ll2xy/Ll2xy.h
+Ll2xy_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+EdgeDetection_SOURCES = ../EdgeDetection/EdgeDetection.cpp\
+							../EdgeDetection/EdgeDetection.h
+EdgeDetection_LDADD= ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+ExpSimplify_SOURCES = ../ExpSimplify/ExpSimplify.cpp\
+							../ExpSimplify/ExpSimplify.h
+ExpSimplify_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Exp2Kml_SOURCES = ../Exp2Kml/Exp2Kml.cpp\
+							../Exp2Kml/Exp2Kml.h
+Exp2Kml_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Kml2Exp_SOURCES = ../Kml2Exp/Kml2Exp.cpp\
+							../Kml2Exp/Kml2Exp.h
+Kml2Exp_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Kriging_SOURCES = ../Kriging/Kriging.cpp\
+							../Kriging/Kriging.h
+Kriging_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+MeshPartition_SOURCES = ../MeshPartition/MeshPartition.cpp\
+									../MeshPartition/MeshPartition.h
+MeshPartition_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(METISLIB) $(GSLLIB)
+
+MeshProfileIntersection_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
+												 ../MeshProfileIntersection/MeshProfileIntersection.h
+MeshProfileIntersection_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+NodeConnectivity_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
+										../NodeConnectivity/NodeConnectivity.h
+NodeConnectivity_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+PointCloudFindNeighbors_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp\
+												 ../PointCloudFindNeighbors/PointCloudFindNeighbors.h
+PointCloudFindNeighbors_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+
+PropagateFlagsFromConnectivity_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp\
+														  ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
+PropagateFlagsFromConnectivity_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Scotch_SOURCES = ../Scotch/Scotch.cpp\
+						  ../Scotch/Scotch.h
+Scotch_LDADD = ${deps} $(SCOTCHLIB) $(MPILIB)
+
+Shp2Exp_SOURCES = ../Shp2Exp/Shp2Exp.cpp\
+							../Shp2Exp/Shp2Exp.h
+Shp2Exp_LDADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+Shp2Kml_SOURCES = ../Shp2Kml/Shp2Kml.cpp\
+							../Shp2Kml/Shp2Kml.h
+Shp2Kml_LDADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+TriaSearch_SOURCES = ../TriaSearch/TriaSearch.cpp\
+								../TriaSearch/TriaSearch.h
+TriaSearch_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+TriMesh_SOURCES = ../TriMesh/TriMesh.cpp\
+							../TriMesh/TriMesh.h
+TriMesh_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB)
+
+TriMeshProcessRifts_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
+											../TriMeshProcessRifts/TriMeshProcessRifts.h
+TriMeshProcessRifts_LDADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+#}}}
Index: /issm/trunk/patches/configure.ac
===================================================================
--- /issm/trunk/patches/configure.ac	(revision 15396)
+++ /issm/trunk/patches/configure.ac	(revision 15396)
@@ -0,0 +1,44 @@
+# Process this file with autoconf to produce a configure script.
+
+#AUTOCONF
+AC_INIT([ISSM],[4.2.5],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_CONFIG_AUX_DIR([./aux-config])         #Put config files in aux-config
+AC_CONFIG_MACRO_DIR([m4])                 #m4 macros are located in m4
+m4_include([m4/issm_options.m4])
+AC_CANONICAL_TARGET                       #Determine the system type
+
+#Compilers
+AC_PROG_CC([icc cccl cl icl gcc])
+AC_PROG_CPP
+AC_PROG_CXX([icpc cccl cl icl g++])
+AC_PROG_F77([ifort g77 gfortran])
+
+#Libraries and linking
+AC_F77_LIBRARY_LDFLAGS
+AC_PATH_XTRA      #figure out X library and include paths
+AC_PROG_RANLIB
+
+#AUTOMAKE
+#Initialize automake and declare foreign so that we don't need a ChangeLog, INSTALL, etc
+AM_INIT_AUTOMAKE([foreign])
+AC_CONFIG_HEADERS([./config.h])   #Config file must be config.h
+AM_SILENT_RULES([yes])           #Do not show compilation command by default
+AM_PROG_CC_C_O
+AM_PROG_AR
+
+#Libtool
+#LT_INIT
+
+#Run issm_options.m4
+ISSM_OPTIONS
+
+#List all Makefiles
+AC_CONFIG_FILES([Makefile
+			src/Makefile
+			src/c/Makefile 
+			src/wrappers/Makefile
+			src/wrappers/matlab/Makefile
+			src/m/Makefile])
+
+#End of configure.ac
+AC_OUTPUT
Index: /issm/trunk/patches/issm_options.m4
===================================================================
--- /issm/trunk/patches/issm_options.m4	(revision 15396)
+++ /issm/trunk/patches/issm_options.m4	(revision 15396)
@@ -0,0 +1,1621 @@
+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=cccl
+			export CXX=cccl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export AR="ar-lib lib"
+			export RANLIB=true
+			OSLIBS="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib"
+		elif  test $VENDOR = intel-win7-64; then
+			export CC=cccl
+			export CXX=cccl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export AR="ar-lib lib"
+			export RANLIB=true
+			OSLIBS="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib 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([unknow 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
+  			*linux*)
+  				if test "${host_cpu}" = "x86_64";
+  				then
+  					MEXLIB=-L"$MATLAB_ROOT/bin/glnxa64/ -lmex"
+  					MEXLINK="-pthread -shared -W2,--version-script,${MATLAB_ROOT}/extern/lib/glnxa64/mexFunction.map";
+  				else
+  					MEXLIB=-L"$MATLAB_ROOT/bin/glnx86/ -lmex"
+  					MEXLINK="-pthread -shared -W2,--version-script,${MATLAB_ROOT}/extern/lib/glnx86/mexFunction.map";
+  				fi
+  				MEXEXT=`$MATLAB_ROOT/bin/mexext`
+  				MEXEXT=".$MEXEXT"
+  			;;
+  			*darwin*)
+  				dnl mex -v gives all the flags for compilation of mex files
+  				dnl if matlab version is 7.9 or more, we must use mexmaci64 (64 bits)
+  				MEXLINK="-O -Wl,-flat_namespace -undefined suppress -arch i386 -bundle -Wl,-exported_symbols_list,$MATLAB_ROOT/extern/lib/maci/mexFunction.map"
+  				MEXLIB=" -L$MATLAB_ROOT/bin/maci/ -lmx -lmex -lmat -lstdc++ -largeArrayDims"
+  				if test $MATLAB_MAJOR -ge 7; then 
+  					 if test $MATLAB_MINOR -ge 9; then 
+  						  MEXLINK="-O -Wl,-flat_namespace -undefined suppress -bundle -Wl,-exported_symbols_list,$MATLAB_ROOT/extern/lib/maci64/mexFunction.map"
+  							 MEXLIB=" -L$MATLAB_ROOT/bin/maci64/ -lmx -lmex -lmat -lstdc++"
+  					 fi
+  				fi
+  				MEXEXT=`$MATLAB_ROOT/bin/mexext`
+  				MEXEXT=".$MEXEXT"
+  			;;
+  			*cygwin*) 
+  				if  test $VENDOR = intel-win7-32; then
+					MATLABLIB="$MATLAB_ROOT/extern/lib/win32/microsoft"
+  					MEXLIB="/link /DLL /export:mexFunction -L$MATLABLIB libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib" 
+  				elif  test $VENDOR = intel-win7-64; then
+					MATLABLIB="$MATLAB_ROOT/extern/lib/win64/microsoft"
+  					MEXLIB="/link /DLL /export:mexFunction -L$MATLABLIB libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib " 
+  				fi
+  				MEXEXT=".$MEXEXT"
+  			;;
+      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_MSG_CHECKING(for triangle headers and libraries)
+
+	if test -d "$TRIANGLE_ROOT"; then
+
+		dnl defaults
+		HAVE_TRIANGLE=yes
+		TRIANGLEINCL=-I$TRIANGLE_ROOT/
+
+		case "${host_os}" in
+				*cygwin*)
+				TRIANGLELIB=$TRIANGLE_ROOT/triangle.lib
+				;;
+				*linux*)
+				TRIANGLELIB=$TRIANGLE_ROOT/triangle.a
+				;;
+				*darwin*)
+				TRIANGLELIB=$TRIANGLE_ROOT/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 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)
+		DAKOTA_VERSION=`cat $DAKOTA_ROOT/include/dakota_config.h | grep "#define PACKAGE_VERSION" | sed 's/#define PACKAGE_VERSION//' | sed 's/ //g' | sed -e 's/\"//g' `
+		AC_MSG_RESULT($DAKOTA_VERSION)
+		AC_DEFINE_UNQUOTED([DAKOTA_VERSION],"$DAKOTA_VERSION",[Dakota version number])
+		case "${host_os}" in
+			*cygwin*)
+				if      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"
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+			;;
+			*linux*)
+				if      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
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+			;;
+			*darwin*)
+				if      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])
+		AC_SUBST([DAKOTAINCL])
+		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)
+	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
+		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_ROOT/include
+		PYTHONLIB="-L$PYTHON_ROOT/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-lib],
+		AS_HELP_STRING([--with-mpi-lib = options],[mpi options, for ex: "-L$MPIROOT -lmpich]),
+		[MPILIB=$withval],[MPILIB=""])
+	
+	AC_ARG_WITH([mpi-include],
+	  AS_HELP_STRING([--with-mpi-include=DIR],[mpi include directory, necessary for parallel build]),
+	  [MPI_INCLUDE=$withval],[MPI_INCLUDE=""])
+	
+	if test -z "$MPILIB" ; then
+		HAVE_MPI=no
+	else
+		if test -z "$MPI_INCLUDE" ; then
+			HAVE_MPI=no
+		else
+			HAVE_MPI=yes
+			MPIINCL=-I"$MPI_INCLUDE"
+			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
+	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 (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="-L$PETSC_ROOT/lib libpetscksp.lib libpetscdm.lib libpetscmat.lib libpetscvec.lib libpetscsnes.lib libpetscts.lib libmpiuni.lib libpetsc.lib"
+			else
+				PETSCLIB="-L$PETSC_ROOT/lib libpetsc.lib"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" libmetis.lib"; fi
+			fi
+			;;
+			*linux*)
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetsc  -lpetscsnes -lpetscts"
+			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 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$BLASLAPACK_ROOT libf2cblas.lib  libf2clapack.lib"
+			;;
+			*linux*)
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lflapack -lfblas " 
+			;;
+			*darwin*)
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -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=""
+		MKLLIB=-L"$MKL_ROOT -lmkl -lmkl_lapack -lmkl_scalapack_ilp64   -lmkl_blacs_sgimpt_ilp64 -lguide  -lpthread"
+		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([frtran 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_DEFINE([_HAVE_IOS_],[1],[with ios.])
+	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_DEFINE([_HAVE_ANDROID_],[1],[with android.])
+	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/scripts/DownloadExternalPackage2.py
===================================================================
--- /issm/trunk/scripts/DownloadExternalPackage2.py	(revision 15396)
+++ /issm/trunk/scripts/DownloadExternalPackage2.py	(revision 15396)
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+# -*- coding: ISO-8859-1 -*-
+
+import os,sys
+import urllib
+
+#Check inputs
+if(len(sys.argv)!=3): raise NameError('usage: ./DownloadExternalPackage.py URL localfile')
+
+url=sys.argv[1];
+localFile=sys.argv[2]
+
+#Remove file if it already exists
+if os.path.exists(localFile):
+	print "File "+ localFile +" already exists and will not be downloaded..."
+	sys.exit()
+
+#Try to download from url
+httpfail=-1
+try:
+	print "Fetching %s" % localFile
+	urllib.urlretrieve(url,localFile)
+	httpfail=0
+except Exception, e:
+	httpfail=1
+
+#Error message in case it failed
+if (httpfail):
+	failureMessage = '''
+===========================================================================
+Unable to download package %s from: %s
+* If URL specified manually - perhaps there is a typo?
+* If your network is disconnected - please reconnect 
+* Alternatively, you can download the above URL manually
+===========================================================================
+''' % (localFile,url)
+	raise RuntimeError(failureMessage)
Index: /issm/trunk/scripts/cppcheck.sh
===================================================================
--- /issm/trunk/scripts/cppcheck.sh	(revision 15396)
+++ /issm/trunk/scripts/cppcheck.sh	(revision 15396)
@@ -0,0 +1,3 @@
+#!/bin/bash
+
+cppcheck -j 8 --include=$ISSM_DIR/config.h --enable=all $ISSM_DIR/src/c 2> CPPCHECK.err
Index: /issm/trunk/scripts/getloc.sh
===================================================================
--- /issm/trunk/scripts/getloc.sh	(revision 15395)
+++ /issm/trunk/scripts/getloc.sh	(revision 15396)
@@ -1,5 +1,5 @@
 #!/bin/bash
 #get number of lines of code
-cloc-1.55.pl $ISSM_DIR/src $ISSM_DIR/m4 --exclude-dir=.svn --exclude-dir=ad  --exclude-dir=android --exclude-ext=exp --exclude-lang=make --out=temp
+cloc-1.55.pl $ISSM_DIR/src $ISSM_DIR/m4 --exclude-dir=.svn --exclude-dir=ad  --exclude-ext=exp --exclude-lang=make --out=temp
 cat temp
 ./cloc2html.py
Index: /issm/trunk/scripts/issmconfiguration.sh
===================================================================
--- /issm/trunk/scripts/issmconfiguration.sh	(revision 15395)
+++ /issm/trunk/scripts/issmconfiguration.sh	(revision 15396)
@@ -11,21 +11,37 @@
 	LIST=`ls`
 	
-	if [[  $# == "0" ]]; then 
-		COUNT=0;
-		for STEP in $LIST
-		do
-			let COUNT=$COUNT+1
-			printf '%3i: %s\n' $COUNT $STEP
-		done
+	if test -d "$JPL_SVN/usr/$USER/configs"; then
+		cd $JPL_SVN/usr/$USER/configs 
+		LIST2=`ls`
+	fi
+	
+	#print choices
+	COUNT=0;
+	printf 'ISSM wide configurations\n'
+	for STEP in $LIST
+	do
+		let COUNT=$COUNT+1
+		printf '%3i: %s\n' $COUNT $STEP
+	done
+	printf 'Personal configuration\n'
+	for STEP in $LIST2
+	do
+		let COUNT=$COUNT+1
+		printf '%3i: %s\n' $COUNT $STEP
+	done
 
-		echo -n "Configuration choice: "
-		read choice 
-	else
-		choice=$1
-	fi
+	echo -n "Configuration choice: "
+	read choice 
 
 	#Now go backto the list and retrieve the name of the configuration file: 
 	COUNT=0;
 	for STEP in $LIST
+	do
+		let COUNT=$COUNT+1
+		if [[ $COUNT == $choice ]]; then
+			configurename=$STEP
+		fi
+	done
+	for STEP in $LIST2
 	do
 		let COUNT=$COUNT+1
@@ -41,6 +57,17 @@
 
 	cd $ISSM_DIR 
+
+	#at this point, was a cleanup of the archive requested? 
+	if [ "$1" == "clean" ]; 
+	then 
+		make uninstall && make distclean
+	fi
+
 	source ./scripts/automakererun.sh 
-	source configs/$configurename
+	if [ -f configs/$configurename ]; then 
+		source configs/$configurename
+	else 
+		source $JPL_SVN/usr/$USER/configs/$configurename
+	fi
 	
 	#we are done, go back to original directory: 
@@ -51,8 +78,3 @@
 fi
 
-
-
-
-
-
 #alias aut='a=`pwd` && cd $ISSM_DIR && ./scripts/automakererun.sh && ./configs/config-macosx64-larour-nopetsc.sh'
Index: sm/trunk/scripts/run.sh
===================================================================
--- /issm/trunk/scripts/run.sh	(revision 15395)
+++ 	(revision )
@@ -1,59 +1,0 @@
-#!/bin/bash
-
-#prepare runs
-NUMCPUS_RUN=7
-NROPTIONS="";
-MATLAB_VERSION="7.6" #7.2,7.4,7.6 and 7.8
-#create softlink to startup {{{1
-cd $ISSM_DIR/test/NightlyRun/
-ln -s $ISSM_DIR/startup.m .
-#}}}
-
-#Launch all tests on different cpus
-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 daily.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
-	exit
-EOF
-
-	#Start run from dailylog directory
-	cd $ISSM_DIR/dailylog/
-
-	#Start test
-	/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
-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
-	rm matlab_log$i.log
-
-done
Index: /issm/trunk/scripts/vie
===================================================================
--- /issm/trunk/scripts/vie	(revision 15396)
+++ /issm/trunk/scripts/vie	(revision 15396)
@@ -0,0 +1,10 @@
+#!/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);}')
+vim $DIR/*.errlog
Index: /issm/trunk/scripts/vil
===================================================================
--- /issm/trunk/scripts/vil	(revision 15395)
+++ /issm/trunk/scripts/vil	(revision 15396)
@@ -1,3 +1,8 @@
 #!/bin/bash
+
+if [ ! -z $EXECUTION_DIR ];
+then
+	EXECUTION_DIR=$ISSM_DIR/execution
+fi
 
 cd $EXECUTION_DIR
Index: sm/trunk/scripts/waitonlock.sh
===================================================================
--- /issm/trunk/scripts/waitonlock.sh	(revision 15395)
+++ 	(revision )
@@ -1,60 +1,0 @@
-#!/bin/bash
-#script version of waitonlock.m
-#function flag=waitonlock(filename,timelimit)
-#%WAITONLOCK - wait for a file
-#%
-#%   This routine will return when a file named 'filename' is written to disk.
-#%   If the time limit given in input is exceeded, return 0
-#%
-#%   Usage:
-#%      flag=waitonlock(filename,timelimit)
-
-#Check input value
-if [ $# -ne 2 ];
-then
-	#no config file specified: exit
-	echo "waitonlock.sh error message: bad usage"
-	exit 0
-fi
-
-#initialization
-TIME=1;
-STEP=1;  #step in seconds
-FILE=$1;
-
-#check time limit
-if [ "$2" == "Inf" ]
-then
-	echo infinity detected
-	LIMIT=999999999;
-else
-	echo not inf
-	let LIMIT=$2*60;
-fi
-
-#display
-echo "waiting for $1 hold on (ctl+c to stop)..."
-
-#Loop till file is found
-while [ $TIME -lt $LIMIT ]
-do
-
-	#lock file exists?
-	if [ -e $FILE ]; then
-		break;
-	fi
-
-	#No-> wait one second
-	sleep $STEP
-	let TIME+=1;
-	echo "waiting $TIME seconds ($TIME < $LIMIT)"
-	dummy=$(ls); #force bash to refresh file list
-
-done
-
-#Compute flag
-if [ $TIME -lt $LIMIT ]; then 
-	exit 1;
-else
-	exit 0;
-fi
Index: /issm/trunk/src/Makefile.am
===================================================================
--- /issm/trunk/src/Makefile.am	(revision 15395)
+++ /issm/trunk/src/Makefile.am	(revision 15396)
@@ -1,5 +1,2 @@
-EXTRA_DIST =  perl pro
-SUBDIRS = c m wrappers 
-if ANDROID
-SUBDIRS += android
-endif
+EXTRA_DIST =  perl
+SUBDIRS = c m wrappers mobile
Index: /issm/trunk/src/c/Makefile.am
===================================================================
--- /issm/trunk/src/c/Makefile.am	(revision 15395)
+++ /issm/trunk/src/c/Makefile.am	(revision 15396)
@@ -19,96 +19,107 @@
 #sources
 #Core sources{{{
-core_sources = ./issm.h\
-					./issm-binding.h\
-					./include/macros.h\
-					./include/typedefs.h\
-					./include/types.h\
-					./include/include.h\
+core_sources = ./main/issm.h\
+			   ./main/globals.h\
+			   ./datastructures/DataSet.h\
+					./datastructures/DataSet.cpp\
+					./datastructures/Object.h\
+					./datastructures/datastructures.h\
 					./classes/classes.h\
-					./classes/objects.h\
-					./classes/objects/Object.h\
 					./classes/gauss/GaussTria.h\
 					./classes/gauss/GaussTria.cpp\
-					./classes/objects/Update.h\
-					./classes/objects/Element.h\
+					./classes/Update.h\
+					./classes/Element.h\
 					./classes/FemModel.h\
 					./classes/FemModel.cpp\
-					./classes/objects/Material.h\
-					./classes/objects/Load.h\
-					./classes/objects/Contour.h\
-					./classes/objects/OptArgs.h\
-					./classes/objects/OptPars.h\
-					./classes/objects/Loads/Friction.h\
-					./classes/objects/Loads/Friction.cpp\
-					./classes/objects/Inputs/TransientInput.h\
-					./classes/objects/Inputs/TransientInput.cpp\
-					./classes/objects/Constraints/SpcTransient.cpp\
-					./classes/objects/Constraints/SpcTransient.h\
-					./classes/objects/IndependentObject.h\
-					./classes/objects/IndependentObject.cpp\
-					./classes/objects/DependentObject.h\
-					./classes/objects/DependentObject.cpp\
+					./classes/Material.h\
+					./classes/Load.h\
+					./classes/Contour.h\
+					./classes/Loads/Friction.h\
+					./classes/Loads/Friction.cpp\
+					./classes/Inputs/TransientInput.h\
+					./classes/Inputs/TransientInput.cpp\
+					./classes/Constraints/SpcTransient.cpp\
+					./classes/Constraints/SpcTransient.h\
+					./classes/IndependentObject.h\
+					./classes/IndependentObject.cpp\
+					./classes/DependentObject.h\
+					./classes/DependentObject.cpp\
 					./classes/DofIndexing.h\
 					./classes/DofIndexing.cpp\
 					./classes/IoModel.h\
 					./classes/IoModel.cpp\
-					./classes/objects/Node.h\
-					./classes/objects/Node.cpp\
-					./classes/objects/Segment.h\
-					./classes/objects/Vertex.h\
-					./classes/objects/Vertex.cpp\
-					./classes/objects/AdolcEdf.h\
-					./classes/IssmComm.h\
-					./classes/IssmComm.cpp\
+					./classes/Contours.h\
+					./classes/Contours.cpp\
+					./classes/Nodes.h\
+					./classes/Nodes.cpp\
+					./classes/Vertices.h\
+					./classes/Vertices.cpp\
+					./classes/Node.h\
+					./classes/Node.cpp\
+					./classes/Segment.h\
+					./classes/Vertex.h\
+					./classes/Vertex.cpp\
 					./classes/Hook.h\
 					./classes/Hook.cpp\
 					./classes/Patch.h\
 					./classes/Patch.cpp\
-					./classes/objects/ElementResults/ElementResultLocal.h\
-					./classes/objects/ElementResults/DoubleElementResult.h\
-					./classes/objects/ElementResults/DoubleElementResult.cpp\
-					./classes/objects/ElementResults/TriaP1ElementResult.h\
-					./classes/objects/ElementResults/TriaP1ElementResult.cpp\
-					./classes/objects/ElementResults/BoolElementResult.h\
-					./classes/objects/ElementResults/BoolElementResult.cpp\
-					./classes/objects/ExternalResults/ExternalResult.h\
-					./classes/objects/ExternalResults/GenericExternalResult.h\
-					./classes/objects/Elements/Tria.h\
-					./classes/objects/Elements/Tria.cpp\
-					./classes/objects/Elements/TriaHook.h\
-					./classes/objects/Elements/TriaHook.cpp\
-					./classes/objects/Elements/TriaRef.h\
-					./classes/objects/Elements/TriaRef.cpp\
-					./classes/objects/Inputs/Input.h\
-					./classes/objects/Inputs/InputLocal.h\
-					./classes/objects/Inputs/TriaP1Input.h\
-					./classes/objects/Inputs/TriaP1Input.cpp\
-					./classes/objects/Inputs/BoolInput.h\
-					./classes/objects/Inputs/BoolInput.cpp\
-					./classes/objects/Inputs/IntInput.h\
-					./classes/objects/Inputs/IntInput.cpp\
-					./classes/objects/Inputs/DoubleInput.h\
-					./classes/objects/Inputs/DoubleInput.cpp\
-					./classes/objects/Inputs/DatasetInput.h\
-					./classes/objects/Inputs/DatasetInput.cpp\
-					./classes/objects/Materials/Matice.h\
-					./classes/objects/Materials/Matice.cpp\
-					./classes/objects/Materials/Matdamageice.h\
-					./classes/objects/Materials/Matdamageice.cpp\
-					./classes/objects/Materials/Matpar.h\
-					./classes/objects/Materials/Matpar.cpp\
-					./classes/objects/Constraints/Constraint.h\
-					./classes/objects/Constraints/SpcStatic.cpp\
-					./classes/objects/Constraints/SpcStatic.h\
-					./classes/objects/Constraints/SpcDynamic.cpp\
-					./classes/objects/Constraints/SpcDynamic.h\
-					./classes/objects/Loads/Penpair.cpp\
-					./classes/objects/Loads/Penpair.h\
-					./classes/objects/Loads/Pengrid.cpp\
-					./classes/objects/Loads/Pengrid.h\
-					./classes/objects/Loads/Icefront.cpp\
-					./classes/objects/Loads/Icefront.h\
-					./classes/objects/Loads/Numericalflux.cpp\
-					./classes/objects/Loads/Numericalflux.h\
+					./classes/ElementResults/ElementResultLocal.h\
+					./classes/ElementResults/DoubleElementResult.h\
+					./classes/ElementResults/DoubleElementResult.cpp\
+					./classes/ElementResults/TriaP1ElementResult.h\
+					./classes/ElementResults/TriaP1ElementResult.cpp\
+					./classes/ElementResults/BoolElementResult.h\
+					./classes/ElementResults/BoolElementResult.cpp\
+					./classes/ExternalResults/Results.h\
+					./classes/ExternalResults/Results.cpp\
+					./classes/ExternalResults/ExternalResult.h\
+					./classes/ExternalResults/GenericExternalResult.h\
+					./classes/Elements/Elements.h\
+					./classes/Elements/Elements.cpp\
+					./classes/Elements/ElementHook.h\
+					./classes/Elements/ElementHook.cpp\
+					./classes/Elements/Tria.h\
+					./classes/Elements/Tria.cpp\
+					./classes/Elements/TriaRef.h\
+					./classes/Elements/TriaRef.cpp\
+					./classes/Inputs/Inputs.h\
+					./classes/Inputs/Inputs.cpp\
+					./classes/Inputs/Input.h\
+					./classes/Inputs/InputLocal.h\
+					./classes/Inputs/TriaInput.h\
+					./classes/Inputs/TriaInput.cpp\
+					./classes/Inputs/BoolInput.h\
+					./classes/Inputs/BoolInput.cpp\
+					./classes/Inputs/IntInput.h\
+					./classes/Inputs/IntInput.cpp\
+					./classes/Inputs/DoubleInput.h\
+					./classes/Inputs/DoubleInput.cpp\
+					./classes/Inputs/DatasetInput.h\
+					./classes/Inputs/DatasetInput.cpp\
+					./classes/Materials/Materials.h\
+					./classes/Materials/Materials.cpp\
+					./classes/Materials/Matice.h\
+					./classes/Materials/Matice.cpp\
+					./classes/Materials/Matdamageice.h\
+					./classes/Materials/Matdamageice.cpp\
+					./classes/Materials/Matpar.h\
+					./classes/Materials/Matpar.cpp\
+					./classes/Constraints/Constraints.h\
+					./classes/Constraints/Constraints.cpp\
+					./classes/Constraints/Constraint.h\
+					./classes/Constraints/SpcStatic.cpp\
+					./classes/Constraints/SpcStatic.h\
+					./classes/Constraints/SpcDynamic.cpp\
+					./classes/Constraints/SpcDynamic.h\
+					./classes/Loads/Loads.h\
+					./classes/Loads/Loads.cpp\
+					./classes/Loads/Penpair.cpp\
+					./classes/Loads/Penpair.h\
+					./classes/Loads/Pengrid.cpp\
+					./classes/Loads/Pengrid.h\
+					./classes/Loads/Icefront.cpp\
+					./classes/Loads/Icefront.h\
+					./classes/Loads/Numericalflux.cpp\
+					./classes/Loads/Numericalflux.h\
 					./classes/matrix/matrixobjects.h\
 					./classes/matrix/ElementMatrix.h\
@@ -116,76 +127,68 @@
 					./classes/matrix/ElementVector.h\
 					./classes/matrix/ElementVector.cpp\
-					./classes/matrix/Matrix.h\
-					./classes/matrix/Vector.h\
-					./classes/objects/Params/Param.h\
-					./classes/objects/Params/GenericParam.h\
-					./classes/objects/Params/BoolParam.cpp\
-					./classes/objects/Params/BoolParam.h\
-					./classes/objects/Params/IntParam.cpp\
-					./classes/objects/Params/IntParam.h\
-					./classes/objects/Params/IntVecParam.cpp\
-					./classes/objects/Params/IntVecParam.h\
-					./classes/objects/Params/IntMatParam.cpp\
-					./classes/objects/Params/IntMatParam.h\
-					./classes/objects/Params/DoubleParam.cpp\
-					./classes/objects/Params/DoubleParam.h\
-					./classes/objects/Params/FileParam.cpp\
-					./classes/objects/Params/FileParam.h\
-					./classes/objects/Params/StringArrayParam.cpp\
-					./classes/objects/Params/StringArrayParam.h\
-					./classes/objects/Params/DoubleMatParam.cpp\
-					./classes/objects/Params/DoubleMatParam.h\
-					./classes/objects/Params/DoubleTransientMatParam.cpp\
-					./classes/objects/Params/DoubleTransientMatParam.h\
-					./classes/objects/Params/DoubleMatArrayParam.cpp\
-					./classes/objects/Params/DoubleMatArrayParam.h\
-					./classes/objects/Params/DoubleVecParam.cpp\
-					./classes/objects/Params/DoubleVecParam.h\
-					./classes/objects/Params/StringParam.cpp\
-					./classes/objects/Params/StringParam.h\
-					./classes/objects/Params/MatrixParam.h\
-					./classes/objects/Params/MatrixParam.cpp\
-					./classes/objects/Params/VectorParam.h\
-					./classes/objects/Params/VectorParam.cpp\
-					./classes/objects/Params/TransientParam.h\
-					./classes/objects/Params/TransientParam.cpp\
-					./classes/objects/Params/DataSetParam.h\
-					./classes/objects/Params/DataSetParam.cpp\
-					./classes/objects/Profiler.h\
-					./classes/objects/Profiler.cpp\
-					./Container/Container.h\
-					./Container/Constraints.h\
-					./Container/Constraints.cpp\
-					./Container/DataSet.h\
-					./Container/DataSet.cpp\
-					./Container/Elements.h\
-					./Container/Elements.cpp\
-					./Container/Inputs.h\
-					./Container/Inputs.cpp\
-					./Container/Loads.h\
-					./Container/Loads.cpp\
-					./Container/Materials.h\
-					./Container/Materials.cpp\
-					./Container/Nodes.h\
-					./Container/Nodes.cpp\
-					./Container/Options.h\
-					./Container/Options.cpp\
-					./Container/Parameters.h\
-					./Container/Parameters.cpp\
-					./Container/Results.h\
-					./Container/Results.cpp\
-					./Container/Vertices.h\
-					./Container/Vertices.cpp\
+					./classes/Params/Parameters.h\
+					./classes/Params/Parameters.cpp\
+					./classes/Params/Param.h\
+					./classes/Params/GenericParam.h\
+					./classes/Params/BoolParam.cpp\
+					./classes/Params/BoolParam.h\
+					./classes/Params/IntParam.cpp\
+					./classes/Params/IntParam.h\
+					./classes/Params/IntVecParam.cpp\
+					./classes/Params/IntVecParam.h\
+					./classes/Params/IntMatParam.cpp\
+					./classes/Params/IntMatParam.h\
+					./classes/Params/DoubleParam.cpp\
+					./classes/Params/DoubleParam.h\
+					./classes/Params/FileParam.cpp\
+					./classes/Params/FileParam.h\
+					./classes/Params/StringArrayParam.cpp\
+					./classes/Params/StringArrayParam.h\
+					./classes/Params/DoubleMatParam.cpp\
+					./classes/Params/DoubleMatParam.h\
+					./classes/Params/DoubleTransientMatParam.cpp\
+					./classes/Params/DoubleTransientMatParam.h\
+					./classes/Params/DoubleMatArrayParam.cpp\
+					./classes/Params/DoubleMatArrayParam.h\
+					./classes/Params/DoubleVecParam.cpp\
+					./classes/Params/DoubleVecParam.h\
+					./classes/Params/StringParam.cpp\
+					./classes/Params/StringParam.h\
+					./classes/Params/MatrixParam.h\
+					./classes/Params/MatrixParam.cpp\
+					./classes/Params/VectorParam.h\
+					./classes/Params/VectorParam.cpp\
+					./classes/Params/TransientParam.h\
+					./classes/Params/TransientParam.cpp\
+					./classes/Params/DataSetParam.h\
+					./classes/Params/DataSetParam.cpp\
+					./classes/Profiler.h\
+					./classes/Profiler.cpp\
 					./shared/shared.h\
-					./shared/Alloc/alloc.h\
-					./shared/Alloc/alloc.cpp\
-					./shared/Alloc/xNewDelete.h\
-					./shared/MemOps/xMemCpy.h\
+					./shared/MemOps/MemOps.h\
 					./shared/Matrix/matrix.h\
 					./shared/Matrix/MatrixUtils.cpp\
+					./shared/io/io.h\
+					./shared/io/Disk/diskio.h\
+					./shared/io/Disk/pfopen.cpp\
+					./shared/io/Disk/pfclose.cpp\
+					./shared/io/Disk/WriteLockFile.cpp\
+					./shared/io/Print/PrintfFunction.cpp\
+					./shared/io/Print/Print.h\
+					./shared/io/Comm/Comm.h\
+					./shared/io/Comm/CommDef.h\
+					./shared/io/Comm/IssmComm.h\
+					./shared/io/Comm/IssmComm.cpp\
+					./shared/LatLong/Ll2xyx.cpp\
+					./shared/LatLong/Xy2llx.cpp\
+					./shared/Enum/Enum.h\
+					./shared/Enum/EnumDefinitions.h\
+					./shared/Enum/EnumToStringx.cpp\
+					./shared/Enum/StringToEnumx.cpp\
 					./shared/Numerics/numerics.h\
+					./shared/Numerics/types.h\
+					./shared/Numerics/constants.h\
 					./shared/Numerics/Verbosity.h\
 					./shared/Numerics/Verbosity.cpp\
-					./shared/Numerics/IsInputConverged.cpp\
 					./shared/Numerics/GaussPoints.h\
 					./shared/Numerics/GaussPoints.cpp\
@@ -196,6 +199,6 @@
 					./shared/Numerics/extrema.cpp\
 					./shared/Numerics/XZvectorsToCoordinateSystem.cpp\
-					./shared/Numerics/UnitConversion.cpp\
-					./shared/Numerics/OptionsFromAnalysis.cpp\
+					./shared/Numerics/OptArgs.h\
+					./shared/Numerics/OptPars.h\
 					./shared/Exceptions/exceptions.h\
 					./shared/Exceptions/Exceptions.cpp\
@@ -206,8 +209,4 @@
 					./shared/Elements/Paterson.cpp\
 					./shared/Elements/Arrhenius.cpp\
-					./shared/Elements/GetVerticesCoordinates.cpp\
-					./shared/Elements/GetLocalDofList.cpp\
-					./shared/Elements/GetGlobalDofList.cpp\
-					./shared/Elements/GetNumberOfDofs.cpp\
 					./shared/Elements/PrintArrays.cpp\
 					./shared/Elements/PddSurfaceMassBalance.cpp\
@@ -217,16 +216,26 @@
 					./toolkits/metis/metisincludes.h\
 					./toolkits/issm/issmtoolkit.h\
-					./toolkits/issm/SeqVec.h\
-					./toolkits/issm/SeqMat.h\
+					./toolkits/issm/IssmToolkitUtils.h\
+					./toolkits/issm/IssmToolkitUtils.cpp\
+					./toolkits/issm/IssmAbsMat.h\
+					./toolkits/issm/IssmAbsVec.h\
+					./toolkits/issm/IssmDenseMat.h\
+					./toolkits/issm/IssmMat.h\
+					./toolkits/issm/IssmSeqVec.h\
+					./toolkits/issm/IssmVec.h\
+					./toolkits/issm/IssmSolver.h\
+					./toolkits/issm/IssmSolver.cpp\
+					./toolkits/issm/Bucket.h\
+					./toolkits/adolc/adolcincludes.h\
+					./toolkits/adolc/AdolcEdf.h\
+					./toolkits/ToolkitOptions.h\
+					./toolkits/ToolkitOptions.cpp\
 					./toolkits/triangle/triangleincludes.h\
+					./toolkits/objects/toolkitobjects.h\
+					./toolkits/objects/Matrix.h\
+					./toolkits/objects/Vector.h\
+					./toolkits/objects/Solver.h\
 					./toolkitsenums.h\
 					./toolkits.h\
-					./io/io.h\
-					./io/Disk/diskio.h\
-					./io/Disk/pfopen.cpp\
-					./io/Disk/pfclose.cpp\
-					./io/Disk/WriteLockFile.cpp\
-					./io/PrintfFunction.cpp\
-					./EnumDefinitions/EnumDefinitions.h\
 					./modules/ModelProcessorx/ModelProcessorx.h\
 					./modules/ModelProcessorx/ModelProcessorx.cpp\
@@ -242,6 +251,6 @@
 					./modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp\
 					./modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp\
-					./modules/ParsePetscOptionsx/ParsePetscOptionsx.h\
-					./modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp\
+					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h\
+					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp\
 					./modules/NodesDofx/NodesDofx.h\
 					./modules/NodesDofx/NodesDofx.cpp\
@@ -250,4 +259,6 @@
 					./modules/VerticesDofx/VerticesDofx.h\
 					./modules/VerticesDofx/VerticesDofx.cpp\
+					./modules/VertexCoordinatesx/VertexCoordinatesx.h\
+					./modules/VertexCoordinatesx/VertexCoordinatesx.cpp\
 					./modules/OutputResultsx/OutputResultsx.h\
 					./modules/OutputResultsx/OutputResultsx.cpp\
@@ -295,8 +306,4 @@
 					./modules/Reduceloadx/Reduceloadx.h\
 					./modules/Reduceloadx/Reduceloadx.cpp\
-					./modules/EnumToStringx/EnumToStringx.cpp\
-					./modules/EnumToStringx/EnumToStringx.h\
-					./modules/StringToEnumx/StringToEnumx.cpp\
-					./modules/StringToEnumx/StringToEnumx.h\
 					./modules/ConstraintsStatex/ConstraintsStatex.cpp\
 					./modules/ConstraintsStatex/ConstraintsStatex.h\
@@ -308,5 +315,4 @@
 					./modules/Solverx/Solverx.cpp\
 					./modules/Solverx/Solverx.h\
-					./modules/Solverx/SolverxSeq.cpp\
 					./modules/VecMergex/VecMergex.cpp\
 					./modules/VecMergex/VecMergex.h\
@@ -315,29 +321,27 @@
 					./modules/InputToResultx/InputToResultx.cpp\
 					./modules/InputToResultx/InputToResultx.h\
-					./modules/InputConvergencex/InputConvergencex.cpp\
-					./modules/InputConvergencex/InputConvergencex.h\
-					./solutions/convergence.cpp\
-					./solutions/ProcessArguments.cpp\
-					./solutions/ResetBoundaryConditions.cpp\
-					./solutions/AnalysisConfiguration.cpp\
-					./solutions/WrapperCorePointerFromSolutionEnum.cpp\
-					./solutions/CorePointerFromSolutionEnum.cpp\
-					./solutions/EnvironmentInit.cpp\
-					./solutions/EnvironmentFinalize.cpp\
-					./solutions/ad_core.cpp\
-					./solvers/solver_linear.cpp\
-					./solvers/solver_nonlinear.cpp\
-					./solvers/solver_newton.cpp\
-					./classes/objects/Options/Option.h\
-					./classes/objects/Options/GenericOption.h\
-					./classes/objects/Options/OptionUtilities.cpp\
-					./classes/objects/Options/OptionUtilities.h\
+					./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.h\
+					./classes/Options/Options.cpp\
+					./classes/Options/Option.h\
+					./classes/Options/GenericOption.h\
+					./classes/Options/OptionUtilities.cpp\
+					./classes/Options/OptionUtilities.h\
 					./classes/RiftStruct.cpp\
 					./classes/RiftStruct.h
 #}}}
 #DAKOTA sources  {{{
-dakota_sources = ./classes/dakota/DakotaPlugin.h\
-					  ./classes/dakota/DakotaPlugin.cpp\
-					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
+dakota_sources = ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
 					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
 					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h\
@@ -348,14 +352,14 @@
 					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
 					  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
-					  ./solutions/dakota_core.cpp\
-					  ./solutions/DakotaSpawnCore.cpp
+					  ./analyses/dakota_core.cpp\
+					  ./analyses/DakotaSpawnCore.h\
+					  ./analyses/DakotaSpawnCore.cpp
 #}}}
 #Transient sources  {{{
 transient_sources  = ./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp \
-					 ./solutions/transient_core.cpp
+							./analyses/transient_core.cpp
 #}}}
 #Steadystate sources  {{{
-steadystate_sources = ./solutions/steadystate_core.cpp\
-					  ./solutions/steadystateconvergence.cpp
+steadystate_sources = ./analyses/steadystate_core.cpp
 #}}}
 #Prognostic sources  {{{
@@ -364,5 +368,5 @@
 					      ./modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp\
 					      ./modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp\
-						  ./solutions/prognostic_core.cpp
+							./analyses/prognostic_core.cpp
 #}}}
 #Thermal sources  {{{
@@ -382,7 +386,7 @@
 					   ./modules/ConstraintsStatex/ThermalIsPresent.cpp\
 					   ./modules/ResetConstraintsx/ThermalConstraintsReset.cpp \
-					   ./solutions/thermal_core.cpp\
-					   ./solutions/enthalpy_core.cpp\
-					   ./solvers/solver_thermal_nonlinear.cpp
+					   ./analyses/thermal_core.cpp\
+					   ./analyses/enthalpy_core.cpp\
+					   ./solutionsequences/solutionsequence_thermal_nonlinear.cpp
 #}}}
 #Control sources  {{{
@@ -425,27 +429,36 @@
 					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp\
 					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h\
-					  ./classes/objects/Inputs/ControlInput.h\
-					  ./classes/objects/Inputs/ControlInput.cpp\
+					  ./classes/Inputs/ControlInput.h\
+					  ./classes/Inputs/ControlInput.cpp\
 					  ./shared/Numerics/BrentSearch.cpp\
 					  ./shared/Numerics/OptimalSearch.cpp \
-					  ./solutions/control_core.cpp\
-					  ./solutions/controltao_core.cpp\
-					  ./solutions/controlrestart.cpp\
-					  ./solutions/controlconvergence.cpp\
-					  ./solutions/objectivefunction.cpp\
-					  ./solutions/gradient_core.cpp\
-					  ./solutions/adjointdiagnostic_core.cpp\
-					  ./solutions/adjointbalancethickness_core.cpp\
-					  ./solutions/AdjointCorePointerFromSolutionEnum.cpp\
-					  ./solvers/solver_adjoint_linear.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  {{{
-hydrology_sources  = ./modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp\
-					      ./modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp\
-					      ./modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp\
-					      ./modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp \
-						  ./solutions/hydrology_core.cpp\
-						  ./solutions/hydrology_core_step.cpp 
+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  {{{
@@ -461,12 +474,7 @@
 					      ./modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp \
 					      ./modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp \
-					      ./modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp \
-						  ./shared/Elements/CoordinateSystemTransform.cpp\
-						  ./shared/Elements/TransformLoadVectorCoord.cpp \
-						  ./shared/Elements/TransformStiffnessMatrixCoord.cpp \
-						  ./shared/Elements/TransformInvStiffnessMatrixCoord.cpp \
-						  ./shared/Elements/TransformSolutionCoord.cpp\
-						  ./solutions/diagnostic_core.cpp\
-						  ./solvers/solver_stokescoupling_nonlinear.cpp
+							./modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp \
+							./analyses/diagnostic_core.cpp\
+							./solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp
 #}}}
 #Balanced sources  {{{
@@ -474,7 +482,7 @@
 					    ./modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp\
 					    ./modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp\
-						./modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp\
-						./solutions/balancethickness_core.cpp \
-						./solutions/dummy_core.cpp
+						 ./modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp\
+						 ./analyses/balancethickness_core.cpp \
+						 ./analyses/dummy_core.cpp
 #}}}
 #Slope sources  {{{
@@ -487,6 +495,24 @@
 					  ./modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp\
 					  ./modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp\
-					  ./solutions/surfaceslope_core.cpp\
-					  ./solutions/bedslope_core.cpp
+					  ./analyses/surfaceslope_core.cpp\
+					  ./analyses/bedslope_core.cpp
+#}}}
+#Gia sources  {{{
+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/GiaDeflectionCorex.h\
+					./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\
+					./classes/GiaDeflectionCoreArgs.h
+
 #}}}
 #Groundingline sources  {{{
@@ -495,6 +521,6 @@
 #}}}
 #Rifts sources  {{{
-rifts_sources = ./classes/objects/Loads/Riftfront.cpp\
-				    ./classes/objects/Loads/Riftfront.h\
+rifts_sources = ./classes/Loads/Riftfront.cpp\
+				    ./classes/Loads/Riftfront.h\
 				    ./modules/ConstraintsStatex/RiftConstraintsState.cpp
 #}}}
@@ -505,71 +531,69 @@
 threed_sources = ./classes/gauss/GaussPenta.h\
 				     ./classes/gauss/GaussPenta.cpp\
-				     ./classes/objects/ElementResults/PentaP1ElementResult.h\
-				     ./classes/objects/ElementResults/PentaP1ElementResult.cpp\
-				     ./classes/objects/Inputs/PentaP1Input.h\
-				     ./classes/objects/Inputs/PentaP1Input.cpp\
-				     ./classes/objects/Elements/Penta.h\
-				     ./classes/objects/Elements/Penta.cpp\
-				     ./classes/objects/Elements/PentaHook.h\
-				     ./classes/objects/Elements/PentaHook.cpp\
-				     ./classes/objects/Elements/PentaRef.h\
-				     ./classes/objects/Elements/PentaRef.cpp
+				     ./classes/ElementResults/PentaP1ElementResult.h\
+				     ./classes/ElementResults/PentaP1ElementResult.cpp\
+				     ./classes/Inputs/PentaP1Input.h\
+				     ./classes/Inputs/PentaP1Input.cpp\
+				     ./classes/Elements/Penta.h\
+				     ./classes/Elements/Penta.cpp\
+				     ./classes/Elements/PentaRef.h\
+				     ./classes/Elements/PentaRef.cpp
 #}}}
 #Bamg sources  {{{
-bamg_sources =  ./classes/bamg/bamgobjects.h\
-				./classes/bamg/BamgGeom.h\
-				./classes/bamg/BamgGeom.cpp\
-				./classes/bamg/BamgMesh.h\
-				./classes/bamg/BamgMesh.cpp\
-				./classes/bamg/BamgOpts.h\
-				./classes/bamg/BamgOpts.cpp\
-				./classes/bamg/CrackedEdge.h\
-				./classes/bamg/CrackedEdge.cpp\
-				./classes/bamg/Curve.h\
-				./classes/bamg/Curve.cpp\
-				./classes/bamg/Direction.h\
-				./classes/bamg/Direction.cpp\
-				./classes/bamg/DoubleAndInt.h\
-				./classes/bamg/Edge.h\
-				./classes/bamg/Edge.cpp\
-				./classes/bamg/GeomEdge.h\
-				./classes/bamg/GeomEdge.cpp\
-				./classes/bamg/GeomSubDomain.h\
-				./classes/bamg/GeomSubDomain.cpp\
-				./classes/bamg/GeomVertex.h\
-				./classes/bamg/GeomVertex.cpp\
-				./classes/bamg/Geometry.cpp\
-				./classes/bamg/Geometry.h\
-				./classes/bamg/ListofIntersectionTriangles.cpp\
-				./classes/bamg/ListofIntersectionTriangles.h\
-				./classes/bamg/EigenMetric.cpp\
-				./classes/bamg/Metric.cpp\
-				./classes/bamg/Metric.h\
-				./classes/bamg/BamgQuadtree.cpp\
-				./classes/bamg/BamgQuadtree.h\
-				./classes/bamg/R2.h\
-				./classes/bamg/SetOfE4.cpp\
-				./classes/bamg/SetOfE4.h\
-				./classes/bamg/SubDomain.h\
-				./classes/bamg/SubDomain.cpp\
-				./classes/bamg/AdjacentTriangle.h\
-				./classes/bamg/AdjacentTriangle.cpp\
-				./classes/bamg/Triangle.cpp\
-				./classes/bamg/Triangle.h\
-				./classes/bamg/BamgVertex.cpp\
-				./classes/bamg/BamgVertex.h\
-				./classes/bamg/VertexOnEdge.h\
-				./classes/bamg/VertexOnEdge.cpp\
-				./classes/bamg/VertexOnGeom.h\
-				./classes/bamg/VertexOnGeom.cpp\
-				./classes/bamg/VertexOnVertex.h\
-				./classes/bamg/VertexOnVertex.cpp\
-				./classes/bamg/Mesh.cpp\
-				./classes/bamg/Mesh.h\
+bamg_sources =  ./bamg/bamgobjects.h\
+				./bamg/BamgGeom.h\
+				./bamg/BamgGeom.cpp\
+				./bamg/BamgMesh.h\
+				./bamg/BamgMesh.cpp\
+				./bamg/BamgOpts.h\
+				./bamg/BamgOpts.cpp\
+				./bamg/CrackedEdge.h\
+				./bamg/CrackedEdge.cpp\
+				./bamg/Curve.h\
+				./bamg/Curve.cpp\
+				./bamg/Direction.h\
+				./bamg/Direction.cpp\
+				./bamg/DoubleAndInt.h\
+				./bamg/Edge.h\
+				./bamg/Edge.cpp\
+				./bamg/GeomEdge.h\
+				./bamg/GeomEdge.cpp\
+				./bamg/GeomSubDomain.h\
+				./bamg/GeomSubDomain.cpp\
+				./bamg/GeomVertex.h\
+				./bamg/GeomVertex.cpp\
+				./bamg/Geometry.cpp\
+				./bamg/Geometry.h\
+				./bamg/ListofIntersectionTriangles.cpp\
+				./bamg/ListofIntersectionTriangles.h\
+				./bamg/EigenMetric.cpp\
+				./bamg/Metric.cpp\
+				./bamg/Metric.h\
+				./bamg/BamgQuadtree.cpp\
+				./bamg/BamgQuadtree.h\
+				./bamg/R2.h\
+				./bamg/SetOfE4.cpp\
+				./bamg/SetOfE4.h\
+				./bamg/SubDomain.h\
+				./bamg/SubDomain.cpp\
+				./bamg/AdjacentTriangle.h\
+				./bamg/AdjacentTriangle.cpp\
+				./bamg/Triangle.cpp\
+				./bamg/det.h \
+				./bamg/Triangle.h\
+				./bamg/BamgVertex.cpp\
+				./bamg/BamgVertex.h\
+				./bamg/VertexOnEdge.h\
+				./bamg/VertexOnEdge.cpp\
+				./bamg/VertexOnGeom.h\
+				./bamg/VertexOnGeom.cpp\
+				./bamg/VertexOnVertex.h\
+				./bamg/VertexOnVertex.cpp\
+				./bamg/Mesh.cpp\
+				./bamg/Mesh.h\
 				./shared/Bamg/Abs.h \
 				./shared/Bamg/BigPrimeNumber.h\
 				./shared/Bamg/BigPrimeNumber.cpp\
 				./shared/Bamg/BinaryRand.h \
-				./shared/Bamg/det.h \
 				./shared/Bamg/Exchange.h \
 				./shared/Bamg/extrema.h \
@@ -584,6 +608,6 @@
 #}}}
 #Kriging sources  {{{
-kriging_sources = ./Container/Observations.h\
-						./Container/Observations.cpp\
+kriging_sources = ./classes/kriging/Observations.h\
+						./classes/kriging/Observations.cpp\
 						./classes/kriging/Variogram.h \
 						./classes/kriging/GaussianVariogram.h\
@@ -603,6 +627,6 @@
 
 #For parallel kriging, only difference is ./modules/Krigingx/pKrigingx.cpp with no multithreading
-pkriging_sources = ./Container/Observations.h\
-						./Container/Observations.cpp\
+pkriging_sources = ./classes/kriging/Observations.h\
+						./classes/kriging/Observations.cpp\
 						./classes/kriging/Variogram.h \
 						./classes/kriging/GaussianVariogram.h\
@@ -637,58 +661,59 @@
 			     ./modules/KMLOverlayx/KMLOverlayx.h\
 			     ./modules/KMLOverlayx/KMLOverlayx.cpp\
-			     ./classes/objects/KML/KML_Attribute.cpp\
-			     ./classes/objects/KML/KML_Attribute.h\
-			     ./classes/objects/KML/KML_Comment.cpp\
-			     ./classes/objects/KML/KML_Comment.h\
-			     ./classes/objects/KML/KML_ColorStyle.cpp\
-			     ./classes/objects/KML/KML_ColorStyle.h\
-			     ./classes/objects/KML/KML_Container.cpp\
-			     ./classes/objects/KML/KML_Container.h\
-			     ./classes/objects/KML/KML_Document.cpp\
-			     ./classes/objects/KML/KML_Document.h\
-			     ./classes/objects/KML/KML_Feature.cpp\
-			     ./classes/objects/KML/KML_Feature.h\
-			     ./classes/objects/KML/KML_File.cpp\
-			     ./classes/objects/KML/KML_File.h\
-			     ./classes/objects/KML/KML_Folder.cpp\
-			     ./classes/objects/KML/KML_Folder.h\
-			     ./classes/objects/KML/KML_Geometry.cpp\
-			     ./classes/objects/KML/KML_Geometry.h\
-			     ./classes/objects/KML/KML_GroundOverlay.cpp\
-			     ./classes/objects/KML/KML_GroundOverlay.h\
-			     ./classes/objects/KML/KML_Icon.cpp\
-			     ./classes/objects/KML/KML_Icon.h\
-			     ./classes/objects/KML/KML_LatLonBox.cpp\
-		  	     ./classes/objects/KML/KML_LatLonBox.h\
-			     ./classes/objects/KML/KML_LinearRing.cpp\
-			     ./classes/objects/KML/KML_LinearRing.h\
-			     ./classes/objects/KML/KML_LineString.cpp\
-			     ./classes/objects/KML/KML_LineString.h\
-			     ./classes/objects/KML/KML_LineStyle.cpp\
-			     ./classes/objects/KML/KML_LineStyle.h\
-			     ./classes/objects/KML/KML_MultiGeometry.cpp\
-			     ./classes/objects/KML/KML_MultiGeometry.h\
-			     ./classes/objects/KML/KML_Object.cpp\
-			     ./classes/objects/KML/KML_Object.h\
-			     ./classes/objects/KML/KML_Overlay.cpp\
-			     ./classes/objects/KML/KML_Overlay.h\
-			     ./classes/objects/KML/KML_Point.cpp\
-			     ./classes/objects/KML/KML_Point.h\
-			     ./classes/objects/KML/KML_Placemark.cpp\
-			     ./classes/objects/KML/KML_Placemark.h\
-			     ./classes/objects/KML/KML_Polygon.cpp\
-			     ./classes/objects/KML/KML_Polygon.h\
-			     ./classes/objects/KML/KML_PolyStyle.cpp\
-			     ./classes/objects/KML/KML_PolyStyle.h\
-			     ./classes/objects/KML/KML_Style.cpp\
-			     ./classes/objects/KML/KML_Style.h\
-			     ./classes/objects/KML/KML_StyleSelector.cpp\
-			     ./classes/objects/KML/KML_StyleSelector.h\
-			     ./classes/objects/KML/KML_SubStyle.cpp\
-			     ./classes/objects/KML/KML_SubStyle.h\
-			     ./classes/objects/KML/KML_Unknown.cpp\
-			     ./classes/objects/KML/KML_Unknown.h\
-			     ./classes/objects/KML/KMLFileReadUtils.cpp\
-			     ./classes/objects/KML/KMLFileReadUtils.h
+			     ./kml/kmlobjects.h\
+			     ./kml/KML_Attribute.cpp\
+			     ./kml/KML_Attribute.h\
+			     ./kml/KML_Comment.cpp\
+			     ./kml/KML_Comment.h\
+			     ./kml/KML_ColorStyle.cpp\
+			     ./kml/KML_ColorStyle.h\
+			     ./kml/KML_Container.cpp\
+			     ./kml/KML_Container.h\
+			     ./kml/KML_Document.cpp\
+			     ./kml/KML_Document.h\
+			     ./kml/KML_Feature.cpp\
+			     ./kml/KML_Feature.h\
+			     ./kml/KML_File.cpp\
+			     ./kml/KML_File.h\
+			     ./kml/KML_Folder.cpp\
+			     ./kml/KML_Folder.h\
+			     ./kml/KML_Geometry.cpp\
+			     ./kml/KML_Geometry.h\
+			     ./kml/KML_GroundOverlay.cpp\
+			     ./kml/KML_GroundOverlay.h\
+			     ./kml/KML_Icon.cpp\
+			     ./kml/KML_Icon.h\
+			     ./kml/KML_LatLonBox.cpp\
+		  	     ./kml/KML_LatLonBox.h\
+			     ./kml/KML_LinearRing.cpp\
+			     ./kml/KML_LinearRing.h\
+			     ./kml/KML_LineString.cpp\
+			     ./kml/KML_LineString.h\
+			     ./kml/KML_LineStyle.cpp\
+			     ./kml/KML_LineStyle.h\
+			     ./kml/KML_MultiGeometry.cpp\
+			     ./kml/KML_MultiGeometry.h\
+			     ./kml/KML_Object.cpp\
+			     ./kml/KML_Object.h\
+			     ./kml/KML_Overlay.cpp\
+			     ./kml/KML_Overlay.h\
+			     ./kml/KML_Point.cpp\
+			     ./kml/KML_Point.h\
+			     ./kml/KML_Placemark.cpp\
+			     ./kml/KML_Placemark.h\
+			     ./kml/KML_Polygon.cpp\
+			     ./kml/KML_Polygon.h\
+			     ./kml/KML_PolyStyle.cpp\
+			     ./kml/KML_PolyStyle.h\
+			     ./kml/KML_Style.cpp\
+			     ./kml/KML_Style.h\
+			     ./kml/KML_StyleSelector.cpp\
+			     ./kml/KML_StyleSelector.h\
+			     ./kml/KML_SubStyle.cpp\
+			     ./kml/KML_SubStyle.h\
+			     ./kml/KML_Unknown.cpp\
+			     ./kml/KML_Unknown.h\
+			     ./kml/KMLFileReadUtils.cpp\
+			     ./kml/KMLFileReadUtils.h
 #}}}
 #Petsc sources  {{{
@@ -719,14 +744,28 @@
 					./toolkits/petsc/objects/PetscVec.h\
 					./toolkits/petsc/objects/PetscVec.cpp\
-					./toolkits/petsc/petscincludes.h\
-					./shared/Numerics/PetscOptionsFromAnalysis.cpp\
-					./modules/Solverx/SolverxPetsc.cpp\
-					./modules/Solverx/DofTypesToIndexSet.cpp
-
+					./toolkits/petsc/objects/PetscSolver.cpp\
+					./toolkits/petsc/objects/PetscSolver.h\
+					./toolkits/petsc/petscincludes.h
+
+#}}}
+#Mumps sources  {{{
+mumps_sources=      ./toolkits/mumps\
+					./toolkits/mumps/mumpsincludes.h\
+					./toolkits/mumps/MpiDenseMumpsSolve.cpp
+#}}}
+#Gsl sources  {{{
+gsl_sources=      ./toolkits/gsl\
+					./toolkits/gsl/gslincludes.h\
+					./toolkits/gsl/DenseGslSolve.cpp
 #}}}
 #Mpi sources  {{{
 mpi_sources= ./toolkits/mpi/mpiincludes.h\
 				./toolkits/mpi/patches/mpipatches.h\
-				./toolkits/mpi/patches/DetermineLocalSize.cpp
+				./toolkits/mpi/patches/DetermineLocalSize.cpp\
+				./toolkits/mpi/patches/DetermineGlobalSize.cpp\
+				./toolkits/mpi/patches/DetermineRowRankFromLocalSize.cpp\
+				./toolkits/mpi/patches/GetOwnershipBoundariesFromRange.cpp\
+				./toolkits/issm/IssmMpiDenseMat.h\
+				./toolkits/issm/IssmMpiVec.h
 #}}}
 #Metis sources  {{{
@@ -739,7 +778,5 @@
 			./shared/Threads/PartitionRange.cpp\
 			./shared/Exp/exp.h\
-			./shared/Exp/IsInPoly.cpp\
-			./shared/Exp/IsInPolySerial.cpp\
-			./shared/Exp/ExpWrite.cpp\
+			./shared/Exp/exp.cpp\
 			./shared/TriMesh/trimesh.h\
 			./shared/TriMesh/AssociateSegmentToElement.cpp\
@@ -762,8 +799,4 @@
 			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp\
 			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp\
-			./modules/Xy2llx/Xy2llx.h\
-			./modules/Xy2llx/Xy2llx.cpp\
-			./modules/Ll2xyx/Ll2xyx.h\
-			./modules/Ll2xyx/Ll2xyx.cpp\
 			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp\
 			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h\
@@ -779,4 +812,6 @@
 			./modules/HoleFillerx/HoleFillerx.cpp\
 			./modules/HoleFillerx/HoleFillerx.h\
+			./modules/EdgeDetectionx/EdgeDetectionx.cpp\
+			./modules/EdgeDetectionx/EdgeDetectionx.h\
 			./modules/AverageFilterx/AverageFilterx.cpp\
 			./modules/AverageFilterx/AverageFilterx.h\
@@ -816,4 +851,12 @@
 endif
 
+if MUMPS
+issm_sources  +=  $(mumps_sources)
+endif
+
+if GSL
+issm_sources  +=  $(gsl_sources)
+endif
+
 if TRANSIENT
 issm_sources  +=  $(transient_sources)
@@ -832,4 +875,8 @@
 endif
 
+if GIA
+issm_sources  +=  $(gia_sources)
+endif
+
 if CONTROL
 issm_sources  +=  $(control_sources)
@@ -884,14 +931,14 @@
 
 libISSMCore_a_SOURCES  = $(issm_sources)
-libISSMCore_a_CXXFLAGS = $(ALLCXXFLAGS)
+libISSMCore_a_CXXFLAGS = $(ALLCXXFLAGS) $(DAKOTAFLAGS)
+libISSMCore_a_FFLAGS = $(AM_FFLAGS)
 
 if SHAREDLIBS
-libISSM_la_SOURCES = solutions/issm.cpp
+libISSM_la_SOURCES = main/issm.cpp
 libISSM_la_LIBADD = libISSMCore.la libISSMOverload.la
 
 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)
-
-libISSMOverload_la_SOURCES = ./shared/String/stricmp.c
+libISSMCore_la_FFLAGS = $(AM_FFLAGS)
 endif
 
@@ -919,5 +966,7 @@
 #}}}
 #Overload library, to overload any non-standard symbols. {{{
-libISSMOverload_a_SOURCES = ./shared/String/stricmp.c
+libISSMOverload_a_SOURCES = ./shared/String/stricmp.cpp\
+							./shared/String/ApiPrintf.cpp
+
 libISSMOverload_a_CFLAGS  = -fPIC -D_C_ $(COPTFLAGS) $(CFLAGS)
 #}}}
@@ -944,10 +993,10 @@
 endif
 
-issm_SOURCES = solutions/issm.cpp
+issm_SOURCES = main/issm.cpp
 issm_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
 
 if KRIGING
 bin_PROGRAMS += kriging
-kriging_SOURCES = solutions/kriging.cpp
+kriging_SOURCES = main/kriging.cpp
 kriging_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
 endif
@@ -980,5 +1029,5 @@
 bin_PROGRAMS +=  issmRose.exe
 issmRose_exe_LDADD = ./libISSMRose.a $(LDADD)
-issmRose_exe_SOURCES = solutions/issm.cpp
+issmRose_exe_SOURCES = main/issm.cpp
 issmRose_exe_CXXFLAGS= -fPIC $(CXXOPTFLAGS) $(COPTFLAGS) 
 LDADD +=  $(ADIC2LIB) 
Index: /issm/trunk/src/c/analyses/AdjointCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointCorePointerFromSolutionEnum.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/AdjointCorePointerFromSolutionEnum.cpp	(revision 15396)
@@ -0,0 +1,46 @@
+/*!\file:  AdjointCorePointerFromSolutionEnum.cpp
+ * \brief: return type of analyses, number of analyses and core solution function.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype){
+
+	/*output: */
+	void (*adjointcore)(FemModel*)=NULL;
+
+	switch(solutiontype){
+
+		case DiagnosticSolutionEnum:
+			adjointcore=&adjointdiagnostic_core;
+			break;
+		case SteadystateSolutionEnum:
+			adjointcore=&adjointdiagnostic_core;
+			break;
+		case BalancethicknessSolutionEnum:
+			adjointcore=&adjointbalancethickness_core;
+			break;
+		case BalancethicknessSoftSolutionEnum:
+			adjointcore=&dummy_core;
+			break;
+		default:
+			_error_("No adjoint has been implemented for solution " << EnumToStringx(solutiontype) << " yet");
+			break;
+	}
+
+	/*Assign output pointer:*/
+	_assert_(padjointcore);
+	*padjointcore=adjointcore;
+
+}
Index: /issm/trunk/src/c/analyses/AnalysisConfiguration.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AnalysisConfiguration.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/AnalysisConfiguration.cpp	(revision 15396)
@@ -0,0 +1,132 @@
+/*!\file:  AnalysisConfiguration.cpp
+ * \brief: return type of analyses, number of analyses 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype){
+
+	/*output: */
+	int  numanalyses;
+	int* analyses=NULL;
+
+	/*Analyses lists*/
+	switch(solutiontype){
+
+		case DiagnosticSolutionEnum:
+			numanalyses=5;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=DiagnosticHorizAnalysisEnum;
+			analyses[1]=DiagnosticVertAnalysisEnum;
+			analyses[2]=DiagnosticHutterAnalysisEnum;
+			analyses[3]=SurfaceSlopeAnalysisEnum;
+			analyses[4]=BedSlopeAnalysisEnum;
+			break;
+
+		case SteadystateSolutionEnum:
+			numanalyses=8;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=DiagnosticHorizAnalysisEnum;
+			analyses[1]=DiagnosticVertAnalysisEnum;
+			analyses[2]=DiagnosticHutterAnalysisEnum;
+			analyses[3]=SurfaceSlopeAnalysisEnum;
+			analyses[4]=BedSlopeAnalysisEnum;
+			analyses[5]=EnthalpyAnalysisEnum;
+			analyses[6]=ThermalAnalysisEnum;
+			analyses[7]=MeltingAnalysisEnum;
+			break;
+
+		case ThermalSolutionEnum:
+			numanalyses=2;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=ThermalAnalysisEnum;
+			analyses[1]=MeltingAnalysisEnum;
+			break;
+
+		case EnthalpySolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=EnthalpyAnalysisEnum;
+			break;
+
+		case HydrologySolutionEnum:
+			numanalyses=5;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=HydrologyShreveAnalysisEnum;
+			analyses[1]=HydrologyDCInefficientAnalysisEnum;
+			analyses[2]=HydrologyDCEfficientAnalysisEnum;
+			analyses[3]=SurfaceSlopeAnalysisEnum;
+			analyses[4]=BedSlopeAnalysisEnum;
+			break;
+
+		case PrognosticSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=PrognosticAnalysisEnum;
+			break;
+
+		case BalancethicknessSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=BalancethicknessAnalysisEnum;
+			break;
+
+		case BalancethicknessSoftSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=BalancethicknessAnalysisEnum;
+			break;
+
+		case SurfaceSlopeSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=SurfaceSlopeAnalysisEnum;
+			break;
+
+		case BedSlopeSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=BedSlopeAnalysisEnum;
+			break;
+
+		case GiaSolutionEnum:
+			numanalyses=1;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=GiaAnalysisEnum;
+			break;
+
+		case TransientSolutionEnum:
+			numanalyses=10-1;
+			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;
+			break;
+
+		default:
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			break;
+	}
+
+	/*Assign output pointers:*/
+	if(pnumanalyses) *pnumanalyses=numanalyses;
+	if(panalyses)    *panalyses=analyses;
+	else              xDelete<int>(analyses);
+}
Index: /issm/trunk/src/c/analyses/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/analyses/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/analyses/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,60 @@
+# 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 15396)
+++ /issm/trunk/src/c/analyses/CorePointerFromSolutionEnum.cpp	(revision 15396)
@@ -0,0 +1,120 @@
+/*!\file:  CorePointerFromSolutionEnum.cpp
+ * \brief: return type of analyses, number of analyses and core solution function.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype){
+
+	/*output: */
+	void (*solutioncore)(FemModel*)=NULL;
+
+	switch(solutiontype){
+
+		case DiagnosticSolutionEnum:
+			#ifdef _HAVE_DIAGNOSTIC_
+			solutioncore=&diagnostic_core;
+			#else
+			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			#endif
+			break;
+		case SteadystateSolutionEnum:
+			#ifdef _HAVE_STEADYSTATE_
+			solutioncore=&steadystate_core;
+			#else
+			_error_("ISSM was not compiled with steady state capabilities. Exiting");
+			#endif
+			break;
+		case ThermalSolutionEnum:
+			#ifdef _HAVE_THERMAL_
+			solutioncore=&thermal_core;
+			#else
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
+			#endif
+			break;
+		case EnthalpySolutionEnum:
+			#ifdef _HAVE_THERMAL_
+			solutioncore=&enthalpy_core;
+			#else
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
+			#endif
+			break;
+		case BalancethicknessSolutionEnum:
+			#ifdef _HAVE_BALANCED_
+			solutioncore=&balancethickness_core;
+			#else
+			_error_("ISSM was not compiled with balanced capabilities. Exiting");
+			#endif
+			break;
+		case BalancethicknessSoftSolutionEnum:
+			#ifdef _HAVE_BALANCED_
+			solutioncore=&dummy_core;
+			#else
+			_error_("ISSM was not compiled with balanced capabilities. Exiting");
+			#endif
+			break;
+		case HydrologySolutionEnum:
+			#ifdef _HAVE_HYDROLOGY_
+			solutioncore=&hydrology_core;
+			#else
+			_error_("ISSM was not compiled with hydrology capabilities. Exiting");
+			#endif
+			break;
+		case SurfaceSlopeSolutionEnum:
+			#ifdef _HAVE_SLOPE_
+			solutioncore=&surfaceslope_core;
+			#else
+			_error_("ISSM was not compiled with slope capabilities. Exiting");
+			#endif
+			break;
+		case BedSlopeSolutionEnum:
+			#ifdef _HAVE_SLOPE_
+			solutioncore=&bedslope_core;
+			#else
+			_error_("ISSM was not compiled with slope capabilities. Exiting");
+			#endif
+			break;
+		case TransientSolutionEnum:
+			#ifdef _HAVE_TRANSIENT_
+			solutioncore=&transient_core;
+			#else
+			_error_("ISSM was not compiled with transient capabilities. Exiting");
+			#endif
+			break;
+		case PrognosticSolutionEnum:
+			#ifdef _HAVE_PROGNOSTIC_
+			solutioncore=&prognostic_core;
+			#else
+			_error_("ISSM was not compiled with prognostic capabilities. Exiting");
+			#endif
+			break;
+
+		case GiaSolutionEnum:
+			#ifdef _HAVE_GIA_
+			solutioncore=&gia_core;
+			#else
+			_error_("ISSM was not compiled with gia capabilities. Exiting");
+			#endif
+			break;
+
+		default:
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			break;
+	}
+
+	/*Assign output pointer:*/
+	_assert_(psolutioncore);
+	*psolutioncore=solutioncore;
+
+}
Index: /issm/trunk/src/c/analyses/DakotaSpawnCore.cpp
===================================================================
--- /issm/trunk/src/c/analyses/DakotaSpawnCore.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/DakotaSpawnCore.cpp	(revision 15396)
@@ -0,0 +1,190 @@
+/*!\file:  DakotaSpawnCore.cpp
+
+ * \brief: run core ISSM solution using Dakota inputs coming from CPU 0.
+ * \sa qmu.cpp DakotaPlugin.cpp
+ *
+ * This routine needs to be understood simultaneously with qmu.cpp and DakotaPlugin. 
+ * DakotaSpawnCoreParallel is called by all CPUS, with CPU 0 holding Dakota variable values, along 
+ * with variable descriptors. 
+ *
+ * DakotaSpawnCoreParallel takes care of broadcasting the variables and their descriptors across the MPI 
+ * ring. Once this is done, we use the variables to modify the inputs for the solution core. 
+ * For ex, if "rho_ice" is provided, for ex 920, we include "rho_ice" in the inputs, then 
+ * call the core with the modified inputs. This is the way we get Dakota to explore the parameter 
+ * spce of the core. 
+ *
+ * Once the core is called, we process the results of the core, and using the processed results, 
+ * we compute response functions. The responses are computed on all CPUS, but they are targeted 
+ * for CPU 0, which will get these values back to the Dakota engine. 
+ *
+ */ 
+
+/*Includes and prototypes: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./analyses.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses);
+void DakotaFree(double** pvariables,char*** pvariables_descriptors,char*** presponses_descriptors,int numvariables,int numresponses);
+/*}}}*/
+
+/*Notice the d_, which prefixes anything that is being provided to us by the Dakota pluggin. Careful. some things are ours, some are dakotas!: */
+int DakotaSpawnCore(double* d_responses, int d_numresponses, double* d_variables, char** d_variables_descriptors,int d_numvariables, void* void_femmodel,int counter){
+
+	char     **responses_descriptors    = NULL;      //these are our! there are only numresponsedescriptors of them, not d_numresponses!!!
+	int        numresponsedescriptors;
+	char      *string                   = NULL;
+	int        solution_type;
+	bool       control_analysis         = false;
+	void     (*solutioncore)(FemModel*) = NULL;
+	FemModel  *femmodel                 = NULL;
+	bool       nodakotacore             = true;
+
+	/*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
+	if(counter==-1)return 0;
+
+	/*cast void_femmodel to FemModel: */
+	femmodel=reinterpret_cast<FemModel*>(void_femmodel);
+
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&responses_descriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+
+	if(VerboseQmu()) _printf0_("qmu iteration: " << counter << "\n");
+
+	/* only cpu 0, running dakota is providing us with variables and variables_descriptors and numresponses: broadcast onto other cpus: */
+	DakotaMPI_Bcast(&d_variables,&d_variables_descriptors,&d_numvariables,&d_numresponses);
+
+	/*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);
+
+	/*Determine solution sequence: */
+	if(VerboseQmu()) _printf0_("Starting " << EnumToStringx(solution_type) << " core:\n");
+	WrapperCorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type,nodakotacore);
+
+	/*Run the core solution sequence: */
+	solutioncore(femmodel);
+
+	/*compute responses: */
+	if(VerboseQmu()) _printf0_("compute dakota responses:\n");
+	femmodel->DakotaResponsesx(d_responses,responses_descriptors,numresponsedescriptors,d_numresponses);
+
+	/*Free ressources:*/
+	DakotaFree(&d_variables,&d_variables_descriptors,&responses_descriptors, d_numvariables, numresponsedescriptors);
+
+	return 1; //this is critical! do not return 0, otherwise, dakota_core will stop running!
+}
+
+void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses){ /*{{{*/
+
+	/* * \brief: broadcast variables_descriptors, variables, numvariables and numresponses
+	 * from cpu 0 to all other cpus.
+	 */ 
+
+	int i;
+	int my_rank;
+
+	/*inputs and outputs: */
+	double* variables=NULL;
+	char**  variables_descriptors=NULL;
+	int     numvariables;
+	int     numresponses;
+
+	/*intermediary: */
+	char* string=NULL;
+	int   string_length;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*recover inputs from pointers: */
+	variables=*pvariables;
+	variables_descriptors=*pvariables_descriptors;
+	numvariables=*pnumvariables;
+	numresponses=*pnumresponses;
+
+	/*numvariables: */
+	MPI_Bcast(&numvariables,1,MPI_INT,0,IssmComm::GetComm()); 
+
+	/*variables:*/
+	if(my_rank!=0)variables=xNew<double>(numvariables);
+	MPI_Bcast(variables,numvariables,MPI_DOUBLE,0,IssmComm::GetComm()); 
+
+	/*variables_descriptors: */
+	if(my_rank!=0){
+		variables_descriptors=xNew<char*>(numvariables);
+	}
+	for(i=0;i<numvariables;i++){
+		if(my_rank==0){
+			string=variables_descriptors[i];
+			string_length=(strlen(string)+1)*sizeof(char);
+		}
+		MPI_Bcast(&string_length,1,MPI_INT,0,IssmComm::GetComm()); 
+		if(my_rank!=0)string=xNew<char>(string_length);
+		MPI_Bcast(string,string_length,MPI_CHAR,0,IssmComm::GetComm()); 
+		if(my_rank!=0)variables_descriptors[i]=string;
+	}
+
+	/*numresponses: */
+	MPI_Bcast(&numresponses,1,MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Assign output pointers:*/
+	*pnumvariables=numvariables;
+	*pvariables=variables;
+	*pvariables_descriptors=variables_descriptors;
+	*pnumresponses=numresponses;
+} /*}}}*/
+void DakotaFree(double** pvariables,char*** pvariables_descriptors,char*** presponses_descriptors,int numvariables,int numresponses){ /*{{{*/
+
+	/*\brief DakotaFree: free allocations on other cpus, not done by Dakota.*/
+
+	int i;
+	int my_rank;
+
+	double  *variables             = NULL;
+	char   **variables_descriptors = NULL;
+	char   **responses_descriptors = NULL;
+	char    *string                = NULL;
+
+	/*recover pointers: */
+	variables=*pvariables;
+	variables_descriptors=*pvariables_descriptors;
+	responses_descriptors=*presponses_descriptors;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*Free variables and variables_descriptors only on cpu !=0*/
+	if(my_rank!=0){
+		xDelete<double>(variables);
+		for(i=0;i<numvariables;i++){
+			string=variables_descriptors[i];
+			xDelete<char>(string);
+		}
+		xDelete<char*>(variables_descriptors);
+	}
+
+	//responses descriptors on every cpu
+	for(i=0;i<numresponses;i++){
+		string=responses_descriptors[i];
+		xDelete<char>(string);
+	}
+	//rest of dynamic allocations.
+	xDelete<char*>(responses_descriptors);
+
+	/*Assign output pointers:*/
+	*pvariables=variables;
+	*pvariables_descriptors=variables_descriptors;
+	*presponses_descriptors=responses_descriptors;
+} /*}}}*/
Index: /issm/trunk/src/c/analyses/DakotaSpawnCore.h
===================================================================
--- /issm/trunk/src/c/analyses/DakotaSpawnCore.h	(revision 15396)
+++ /issm/trunk/src/c/analyses/DakotaSpawnCore.h	(revision 15396)
@@ -0,0 +1,4 @@
+#ifndef _DAKOTA_SPAWN_CORE_
+#define _DAKOTA_SPAWN_CORE_
+int  DakotaSpawnCore(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, void* femmodel,int counter);
+#endif
Index: /issm/trunk/src/c/analyses/EnvironmentFinalize.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnvironmentFinalize.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/EnvironmentFinalize.cpp	(revision 15396)
@@ -0,0 +1,28 @@
+/*!\file:  EnvironmentFinalize.cpp
+ * \brief: finalize Petsc, MPI, you name it
+ */ 
+#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 "../shared/shared.h"
+
+void EnvironmentFinalize(void){
+
+	#ifdef _HAVE_MPI_
+
+	/*Make sure we are all here*/
+	MPI_Barrier(MPI_COMM_WORLD);
+
+	/*Print closing statement*/
+	int my_rank;
+	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
+	if(!my_rank) printf("closing MPI\n");
+
+	/*Finalize: */
+	MPI_Finalize();
+
+	#endif
+}
Index: /issm/trunk/src/c/analyses/EnvironmentInit.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnvironmentInit.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/EnvironmentInit.cpp	(revision 15396)
@@ -0,0 +1,37 @@
+/*!\file:  EnvironmentInit.cpp
+ * \brief: initialize Petsc, MPI, you name it
+ */ 
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <stdio.h>
+#include "../toolkits/toolkits.h"
+
+COMM EnvironmentInit(int argc,char** argv){
+
+	/*Output*/
+	COMM comm = 0;
+
+	/*Initialize MPI environment: */
+	#if defined(_HAVE_MPI_)
+	MPI_Init(&argc,&argv);
+	comm = MPI_COMM_WORLD;
+	#else
+	comm = 1; //bogus number for comm, which does not exist anyway.
+	#endif
+
+	/*Print Banner*/
+	int my_rank = 0;
+	#ifdef _HAVE_MPI_
+	MPI_Comm_rank(comm,&my_rank);
+	#endif
+	if(!my_rank) printf("\n");
+	if(!my_rank) printf("Ice Sheet System Model (%s) version  %s\n",PACKAGE_NAME,PACKAGE_VERSION);
+	if(!my_rank) printf("(website: %s contact: %s)\n",PACKAGE_URL,PACKAGE_BUGREPORT);
+	if(!my_rank) printf("\n");
+
+	/*Return communicator*/
+	return comm;
+}
Index: /issm/trunk/src/c/analyses/ProcessArguments.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ProcessArguments.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/ProcessArguments.cpp	(revision 15396)
@@ -0,0 +1,57 @@
+/*!\file:  ProcessArguments.cpp
+ * \brief: process arguments
+ */ 
+
+#include <stdio.h>
+#include <cstring>
+
+#include "../shared/shared.h"
+
+void ProcessArguments(int* solution_type,char** pbinfilename,char** poutbinfilename,char** ptoolkitsfilename,char** plockfilename,char** prootpath, int argc,char **argv){
+
+	char *modelname      = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *toolkitsfilename  = NULL;
+	char *lockfilename   = NULL;
+	char *rootpath       = NULL;
+	char *rootpatharg    = NULL;
+
+	/*Check input arguments*/
+	if(argc<2)_error_("Usage error: no solution requested");
+	if(argc<3)_error_("Usage error: missing execution directory");
+	if(argc<4)_error_("Usage error: missing model name");
+
+	/*Get requested solution*/
+	*solution_type=StringToEnumx(argv[1]);
+
+	rootpatharg=argv[2];
+	if(strcmp(strstr(rootpatharg,"/"),"/")!=0){ 
+		rootpath       = xNew<char>(strlen(rootpatharg)+2); sprintf(rootpath,"%s/",rootpatharg);
+	}
+	else{
+		rootpath       = xNew<char>(strlen(rootpatharg)+1); sprintf(rootpath,"%s",rootpatharg);
+	}
+
+	modelname=argv[3];
+	if(strstr(modelname,rootpath)==NULL){
+		binfilename    = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s%s",rootpath,modelname,".bin");
+		outbinfilename = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s%s",rootpath,modelname,".outbin");
+		toolkitsfilename  = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".toolkits") +1); sprintf(toolkitsfilename, "%s%s%s",rootpath,modelname,".toolkits");
+		lockfilename   = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s%s",rootpath,modelname,".lock");
+	}
+	else{
+		binfilename    = xNew<char>(strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s",modelname,".bin");
+		outbinfilename = xNew<char>(strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s",modelname,".outbin");
+		toolkitsfilename  = xNew<char>(strlen(modelname)+strlen(".toolkits") +1); sprintf(toolkitsfilename, "%s%s",modelname,".toolkits");
+		lockfilename   = xNew<char>(strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s",modelname,".lock");
+	}
+
+	/*Clean up and assign output pointer*/
+	*pbinfilename=binfilename;
+	*poutbinfilename=outbinfilename;
+	*ptoolkitsfilename=toolkitsfilename;
+	*plockfilename=lockfilename;
+	*prootpath=rootpath;
+
+}
Index: /issm/trunk/src/c/analyses/ResetBoundaryConditions.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ResetBoundaryConditions.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/ResetBoundaryConditions.cpp	(revision 15396)
@@ -0,0 +1,31 @@
+/*!\file: ResetBoundaryConditions.cpp
+ * \brief: change boundary conditions of a model, using a solution vector from another analysis
+ */ 
+
+#include "../classes/classes.h"
+#include "../modules/modules.h"
+#include "../shared/io/io.h"
+
+void ResetBoundaryConditions(FemModel* femmodel, int analysis_type){
+
+	/*variables: */
+	Vector<IssmDouble>*    yg    = NULL;
+	Nodes *nodes = NULL;
+
+	if(VerboseSolution()) _printf0_("   updating boundary conditions...\n");
+
+	/*set current analysis: */
+	femmodel->SetCurrentConfiguration(analysis_type);
+
+	/*recover nodes: */
+	nodes=femmodel->nodes;
+
+	/*retrieve boundary conditions from element inputs :*/
+	GetSolutionFromInputsx( &yg, femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,  femmodel->parameters);
+
+	/*update spcs using this new vector of constraints: */
+	UpdateDynamicConstraintsx(femmodel->constraints,femmodel->nodes,femmodel->parameters,yg);
+
+	/*Free ressources:*/
+	delete yg;
+}
Index: /issm/trunk/src/c/analyses/WrapperCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/analyses/WrapperCorePointerFromSolutionEnum.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/WrapperCorePointerFromSolutionEnum.cpp	(revision 15396)
@@ -0,0 +1,57 @@
+/*!\file:  WrapperCorePointerFromSolutionEnum.cpp
+ * \brief: return type of analyses, number of analyses and core solution function.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore){
+
+	/*output: */
+	void (*solutioncore)(FemModel*)=NULL;
+
+	/*parameters: */
+	bool control_analysis=false;
+	bool tao_analysis=false;
+	bool dakota_analysis=false;
+
+	/* retrieve some parameters that tell us whether wrappers are allowed, or whether we return 
+	 * a pure core. Wrappers can be dakota_core (which samples many solution_cores) or control_core (which 
+	 * carries out adjoint based inversion on a certain core: */
+	parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	parameters->FindParam(&tao_analysis,InversionTaoEnum);
+
+	if(nodakotacore)dakota_analysis=false;
+
+	if(dakota_analysis){
+		#ifdef _HAVE_DAKOTA_
+		solutioncore=dakota_core;
+		#else
+		_error_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
+		#endif
+	}
+	else if(control_analysis){
+		#ifdef _HAVE_CONTROL_
+		if(tao_analysis) solutioncore=controltao_core;
+		else solutioncore=control_core;
+		#else
+		_error_("ISSM was not compiled with control support, cannot carry out control analysis!");
+		#endif
+	}
+	else CorePointerFromSolutionEnum(&solutioncore,parameters,solutiontype);  /*This means we retrieve a core solution that is not a wrapper*/
+
+	/*Assign output pointer:*/
+	_assert_(psolutioncore);
+	*psolutioncore=solutioncore;
+
+}
Index: /issm/trunk/src/c/analyses/ad_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ad_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/ad_core.cpp	(revision 15396)
@@ -0,0 +1,305 @@
+/*!\file ad_core
+ * \brief: compute outputs from the AD mode,  using our dependents and independents, and drivers available in Adolc.
+ */
+
+/*Includes: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <set>
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+/*}}}*/
+
+void ad_core(FemModel* femmodel){
+
+	/*diverse: */
+	int     i;
+	int     dummy;
+	int     num_dependents;
+	int     num_independents;
+	bool    isautodiff       = false;
+	char   *driver           = NULL;
+	size_t  tape_stats[11];
+
+	/*state variables: */
+	IssmDouble *axp = NULL;
+	double     *xp  = NULL;
+
+	/*AD mode on?: */
+	femmodel->parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+
+	if(isautodiff){
+
+		#ifdef _HAVE_ADOLC_
+
+			/*First, stop tracing: */
+			trace_off();
+
+			/*preliminary checks: */
+			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");
+
+			/*retrieve state variable: */
+			femmodel->parameters->FindParam(&axp,&dummy,AutodiffXpEnum);
+
+			/* driver argument */
+			xp=xNew<double>(num_independents);
+			for(i=0;i<num_independents;i++){
+				xp[i]=reCast<double,IssmDouble>(axp[i]);
+			}
+
+			/*get the EDF pointer:*/
+			ext_diff_fct *anEDF_for_solverx_p=dynamic_cast<GenericParam<Adolc_edf> * >(femmodel->parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
+
+			/*Branch according to AD driver: */
+			femmodel->parameters->FindParam(&driver,AutodiffDriverEnum);
+
+			/* these are always needed regardless of the interpreter */
+			anEDF_for_solverx_p->dp_x=xNew<double>(anEDF_for_solverx_p->max_n);
+			anEDF_for_solverx_p->dp_y=xNew<double>(anEDF_for_solverx_p->max_m);
+
+			if (strcmp(driver,"fos_forward")==0){
+
+				int     anIndepIndex;
+				double *tangentDir         = NULL;
+				double *jacTimesTangentDir = NULL;
+				double *theOutput          = NULL;
+
+				/*retrieve direction index: */
+				femmodel->parameters->FindParam(&anIndepIndex,AutodiffFosForwardIndexEnum);
+
+				if (anIndepIndex<0 || anIndepIndex>=num_independents) _error_("index value for AutodiffFosForwardIndexEnum should be in [0,num_independents-1]");
+
+				tangentDir=xNewZeroInit<double>(num_independents);
+				tangentDir[anIndepIndex]=1.0;
+
+				jacTimesTangentDir=xNew<double>(num_dependents);
+				theOutput=xNew<double>(num_dependents);
+
+				/*set the forward method function pointer: */
+				anEDF_for_solverx_p->fos_forward=EDF_fos_forward_for_solverx;
+
+				/*allocate the space for the parameters to invoke the EDF fos_forward:*/
+				anEDF_for_solverx_p->dp_X=xNew<double>(anEDF_for_solverx_p->max_n);
+				anEDF_for_solverx_p->dp_Y=xNew<double>(anEDF_for_solverx_p->max_m);
+
+				/*call driver: */
+				fos_forward(1,num_dependents,num_independents, 0, xp, tangentDir, theOutput, jacTimesTangentDir );
+
+				/*add to results*/
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,jacTimesTangentDir,num_dependents,1,1,0.0));
+
+				/*free resources :*/
+				xDelete(theOutput);
+				xDelete(jacTimesTangentDir);
+				xDelete(tangentDir);
+			}
+			else if ((strcmp(driver,"fov_forward")==0) || (strcmp(driver,"fov_forward_all")==0)){
+
+				int      tangentDirNum;
+				int      dummy;
+				int     *indepIndices  = NULL;
+				double **jacTimesSeed  = NULL;
+				double **seed          = NULL;
+				double  *theOutput     = NULL;
+				std::set<unsigned int> anIndexSet;
+
+				/*retrieve directions:*/
+				if (strcmp(driver,"fov_forward_all")==0){
+					tangentDirNum=num_independents;
+					indepIndices=xNewZeroInit<int>(tangentDirNum);
+					for(i=0;i<num_independents;i++)indepIndices[i]=1;
+				}
+				else{
+					femmodel->parameters->FindParam(&indepIndices,&tangentDirNum,&dummy,AutodiffFovForwardIndicesEnum);
+				}
+
+				/*Some checks: */
+				if (tangentDirNum<1 || tangentDirNum>num_independents) _error_("tangentDirNum should be in [1,num_independents]");
+
+				/* full Jacobian or Jacobian projection:*/
+				jacTimesSeed=xNew<double>(num_dependents,tangentDirNum);
+
+				/*set the forward method function pointers: */
+				anEDF_for_solverx_p->fov_forward=EDF_fov_forward_for_solverx;
+				// anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
+
+				/*allocate the space for the parameters to invoke EDF fov_forward:*/
+				anEDF_for_solverx_p->dpp_X=xNew<double>(anEDF_for_solverx_p->max_n, tangentDirNum);
+				anEDF_for_solverx_p->dpp_Y=xNew<double>(anEDF_for_solverx_p->max_m, tangentDirNum);
+
+				/*seed matrix: */
+				seed=xNewZeroInit<double>(num_independents,tangentDirNum);
+
+				/*collect indices in a set to prevent accidental duplicates as long as we don't do compression:*/
+				for (int i=0; i<tangentDirNum; ++i) {
+					/* make sure the index is in range*/
+					if (indepIndices[i]>num_independents) {
+						_error_("indepIndices values must be in [0,num_independents-1]");
+					}
+					if (anIndexSet.find(indepIndices[i])!=anIndexSet.end()) {
+						_error_("duplicate indepIndices values are not allowed until we implement Jacobian decompression");
+					}
+					anIndexSet.insert(indepIndices[i]);
+					/* now populate the seed matrix from the set of independent indices;
+					 * simple setup with a single 1.0 per column and at most a single 1.0 per row*/
+					seed[indepIndices[i]][i]=1.0;
+				}
+
+				/*allocate output: */
+				theOutput=xNew<double>(num_dependents);
+
+				/*call driver: */
+				fov_forward(1,num_dependents,num_independents, tangentDirNum, xp, seed, theOutput, jacTimesSeed );
+				/*Free resources: */
+				xDelete(theOutput);
+				xDelete(indepIndices);
+				xDelete(seed);
+
+				/*add to results: */
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,*jacTimesSeed,num_dependents*tangentDirNum,1,1,0.0));
+
+				/*Free resources: */
+				xDelete(jacTimesSeed);
+				xDelete(indepIndices);
+			}
+			else if (strcmp(driver,"fos_reverse")==0) {
+
+				int     aDepIndex=0;
+				double *aWeightVector=NULL;
+				double *weightVectorTimesJac=NULL;
+
+				/*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;
+
+				weightVectorTimesJac=xNew<double>(num_independents);
+
+				/*set the forward method function pointer: */
+				anEDF_for_solverx_p->fos_reverse=EDF_fos_reverse_for_solverx;
+
+				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
+				anEDF_for_solverx_p->dp_U=xNew<double>(anEDF_for_solverx_p->max_m);
+				anEDF_for_solverx_p->dp_Z=xNew<double>(anEDF_for_solverx_p->max_n);
+
+				/*call driver: */
+				fos_reverse(1,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
+
+				/*add to results*/
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,weightVectorTimesJac,num_independents,1,1,0.0));
+
+				/*free resources :*/
+				xDelete(weightVectorTimesJac);
+				xDelete(aWeightVector);
+			}
+			else if ((strcmp(driver,"fov_reverse")==0) || (strcmp(driver,"fov_reverse_all")==0)){
+
+				int* depIndices=NULL;
+				int weightNum;
+				int dummy;
+				double **weightsTimesJac=NULL;
+				double **weights=NULL;
+				std::set<unsigned int> anIndexSet;
+
+				/*retrieve directions:*/
+				if (strcmp(driver,"fov_reverse_all")==0){
+					weightNum=num_dependents;
+					depIndices=xNewZeroInit<int>(weightNum);
+					for(i=0;i<num_dependents;i++)depIndices[i]=1;
+				}
+				else{
+					femmodel->parameters->FindParam(&depIndices,&weightNum,&dummy,AutodiffFovForwardIndicesEnum);
+				}
+
+				/*Some checks: */
+				if (weightNum<1 || weightNum>num_dependents) _error_("tangentDirNum should be in [1,num_dependents]");
+
+				/* full Jacobian or Jacobian projection:*/
+				weightsTimesJac=xNew<double>(weightNum,num_independents);
+
+				/*set the forward method function pointers: */
+				anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
+
+				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
+				anEDF_for_solverx_p->dpp_U=xNew<double>(weightNum,anEDF_for_solverx_p->max_m);
+				anEDF_for_solverx_p->dpp_Z=xNew<double>(weightNum,anEDF_for_solverx_p->max_n);
+
+				/*seed matrix: */
+				weights=xNewZeroInit<double>(weightNum,num_dependents);
+
+				/*collect indices in a set to prevent accidental duplicates as long as we don't do compression:*/
+				for (int i=0; i<weightNum; ++i) {
+					/* make sure the index is in range*/
+					if (depIndices[i]>num_dependents) {
+						_error_("depIndices values must be in [0,num_dependents-1]");
+					}
+					if (anIndexSet.find(depIndices[i])!=anIndexSet.end()) {
+						_error_("duplicate depIndices values are not allowed until we implement Jacobian decompression");
+					}
+					anIndexSet.insert(depIndices[i]);
+					/* now populate the seed matrix from the set of independent indices;
+					 * simple setup with a single 1.0 per column and at most a single 1.0 per row*/
+					weights[depIndices[i]][i]=1.0;
+				}
+
+				/*call driver: */
+				fov_reverse(1,num_dependents,num_independents, weightNum, weights, weightsTimesJac );
+
+				/*add to results: */
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,*weightsTimesJac,weightNum*num_independents,1,1,0.0));
+
+				/*Free resources: */
+				xDelete(weights);
+				xDelete(weightsTimesJac);
+				xDelete(depIndices);
+			}
+			else _error_("driver: " << driver << " not yet supported!");
+
+			/* delete the allocated space for the parameters:*/
+			xDelete(anEDF_for_solverx_p->dp_x);
+			xDelete(anEDF_for_solverx_p->dp_X);
+			xDelete(anEDF_for_solverx_p->dpp_X);
+			xDelete(anEDF_for_solverx_p->dp_y);
+			xDelete(anEDF_for_solverx_p->dp_Y);
+			xDelete(anEDF_for_solverx_p->dpp_Y);
+			xDelete(anEDF_for_solverx_p->dp_U);
+			xDelete(anEDF_for_solverx_p->dpp_U);
+			xDelete(anEDF_for_solverx_p->dp_Z);
+			xDelete(anEDF_for_solverx_p->dpp_Z);
+
+			/*Print statistics:*/
+			tapestats(1,tape_stats); //reading of tape statistics
+			if(VerboseAutodiff()){
+				_printf0_("   ADOLC statistics: \n");
+				_printf0_("   "<<setw(45)<<left<<"Number of independents: " <<tape_stats[0] << "\n");
+				_printf0_("   "<<setw(45)<<left<<"Number of dependents: " <<tape_stats[1] << "\n");
+				_printf0_("   "<<setw(45)<<left<<"Maximal number of live active variables: " <<tape_stats[2] << "\n");
+				_printf0_("   "<<setw(45)<<left<<"Size of value stack (number of overwrites): " <<tape_stats[3] << "\n");
+				_printf0_("   "<<setw(45)<<left<<"Buffer size (a multiple of eight): " <<tape_stats[4] << "\n");
+				_printf0_("   "<<setw(45)<<left<<"Total number of operations recorded: " <<tape_stats[5] << "\n");
+			}
+			if(VerboseAutodiff())_printf0_("   end AD core\n");
+
+			/*Free resources: */
+			xDelete(xp);
+			xDelete(axp); 
+		#else
+			_error_("Should not be requesting AD drivers when an AD library is not available!");
+		#endif
+	}
+}
Index: /issm/trunk/src/c/analyses/adjointbalancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/adjointbalancethickness_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/adjointbalancethickness_core.cpp	(revision 15396)
@@ -0,0 +1,38 @@
+/*!\file:  adjointbalancethickness_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 adjointbalancethickness_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*retrieve parameters:*/
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	/*compute thickness */
+	if(VerboseSolution()) _printf0_("   computing thickness\n");
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	/*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(BalancethicknessAnalysisEnum,AdjointBalancethicknessAnalysisEnum);
+	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,AdjointEnum);
+	}
+}
Index: /issm/trunk/src/c/analyses/adjointdiagnostic_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/adjointdiagnostic_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/adjointdiagnostic_core.cpp	(revision 15396)
@@ -0,0 +1,46 @@
+/*!\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/analyses.h
===================================================================
--- /issm/trunk/src/c/analyses/analyses.h	(revision 15396)
+++ /issm/trunk/src/c/analyses/analyses.h	(revision 15396)
@@ -0,0 +1,58 @@
+/*
+ * analyses.h: 
+ */
+
+#ifndef _ANALYSES_H_
+#define _ANALYSES_H_
+
+/*forward declarations: */
+struct OptArgs;
+class FemModel;
+class Parameters;
+template <class doubletype> class Matrix;
+template <class doubletype> class Vector;
+
+#include "../shared/io/Comm/Comm.h"
+#include "../shared/Numerics/types.h"
+
+/*cores: */
+void adjointdiagnostic_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 hydrology_core(FemModel* femmodel);
+void thermal_core(FemModel* femmodel);
+void enthalpy_core(FemModel* femmodel);
+void surfaceslope_core(FemModel* femmodel);
+void bedslope_core(FemModel* femmodel);
+void control_core(FemModel* femmodel);
+void controltao_core(FemModel* femmodel);
+void prognostic_core(FemModel* femmodel);
+void balancethickness_core(FemModel* femmodel);
+void slopecompute_core(FemModel* femmodel);
+void steadystate_core(FemModel* femmodel);
+void transient_core(FemModel* femmodel);
+void dakota_core(FemModel* femmodel);
+void ad_core(FemModel* femmodel);
+void dummy_core(FemModel* femmodel);
+void gia_core(FemModel* femmodel);
+IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs);
+
+//optimization
+int GradJSearch(IssmDouble* search_vector,FemModel* femmodel,int step);
+
+//diverse
+void ProcessArguments(int* solution,char** pbinname,char** poutbinname,char** ptoolkitsname,char** plockname,char** prootpath,int argc,char **argv);
+void WriteLockFile(char* filename);
+void ResetBoundaryConditions(FemModel* femmodel, int analysis_type);
+COMM EnvironmentInit(int argc,char** argv);
+void EnvironmentFinalize(void);
+void PrintBanner(void);
+
+//solution configuration
+void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype);
+void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype);
+void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore=false);
+void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype);
+
+#endif
Index: /issm/trunk/src/c/analyses/balancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/balancethickness_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/balancethickness_core.cpp	(revision 15396)
@@ -0,0 +1,31 @@
+/*!\file: balancethickness_core.cpp
+ * \brief: core of the balancethickness 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 balancethickness_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*activate formulation: */
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	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);
+	}
+
+}
Index: /issm/trunk/src/c/analyses/bedslope_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/bedslope_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/bedslope_core.cpp	(revision 15396)
@@ -0,0 +1,34 @@
+/*!\file: bedslope_core.cpp
+ * \brief: core of the slope 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 bedslope_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("   computing slope\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(BedSlopeAnalysisEnum,BedSlopeXAnalysisEnum);
+	solutionsequence_linear(femmodel);
+	femmodel->SetCurrentConfiguration(BedSlopeAnalysisEnum,BedSlopeYAnalysisEnum);
+	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,BedSlopeXEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BedSlopeYEnum);
+	}
+
+}
Index: /issm/trunk/src/c/analyses/control_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/control_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/control_core.cpp	(revision 15396)
@@ -0,0 +1,148 @@
+/*!\file: control_core.cpp
+ * \brief: core of the control solution 
+ */ 
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+/*Local prototypes*/
+bool controlconvergence(IssmDouble J, IssmDouble tol_cm);
+
+void control_core(FemModel* femmodel){
+
+	int     i;
+
+	/*parameters: */
+	int        num_controls,num_responses;
+	int        nsteps;
+	IssmDouble tol_cm;
+	bool       cm_gradient;
+	int        dim;
+	int        solution_type;
+	bool       isstokes;
+	bool       dakota_analysis = false;
+
+	int        *control_type   = NULL;
+	IssmDouble *responses      = NULL;
+	int        *step_responses = NULL;
+	IssmDouble *maxiter        = NULL;
+	IssmDouble *cm_jump        = NULL;
+
+	/*intermediary: */
+	IssmDouble search_scalar = 1;
+	OptArgs    optargs;
+	OptPars    optpars;
+
+	/*Solution and Adjoint core pointer*/
+	void (*solutioncore)(FemModel*) = NULL;
+	void (*adjointcore)(FemModel*)  = NULL;
+
+	/*output: */
+	IssmDouble* J=NULL;
+
+	/*Recover parameters used throughout the solution*/
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+	femmodel->parameters->FindParam(&responses,NULL,NULL,InversionCostFunctionsEnum);
+	femmodel->parameters->FindParam(&nsteps,InversionNstepsEnum);
+	femmodel->parameters->FindParam(&maxiter,NULL,InversionMaxiterPerStepEnum);
+	femmodel->parameters->FindParam(&cm_jump,NULL,InversionStepThresholdEnum);
+	femmodel->parameters->FindParam(&tol_cm,InversionCostFunctionThresholdEnum);
+	femmodel->parameters->FindParam(&cm_gradient,InversionGradientOnlyEnum);
+	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+
+	/*out of solution_type, figure out solution core and adjoint function pointer*/
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+
+	/*Launch once a complete solution to set up all inputs*/
+	if(VerboseControl()) _printf0_("   preparing initial solution\n");
+	if(isstokes) solutioncore(femmodel);
+
+	/*Initialize responses: */
+	J=xNew<IssmDouble>(nsteps);
+	step_responses=xNew<int>(num_responses);
+
+	/*Initialize some of the BrentSearch arguments: */
+	optargs.femmodel=femmodel;
+	optpars.xmin=0; optpars.xmax=1;
+
+	/*Start looping: */
+	for(int n=0;n<nsteps;n++){
+
+		/*Display info*/
+		if(VerboseControl()) _printf0_("\n" << "   control method step " << n+1 << "/" << nsteps << "\n");
+		for(i=0;i<num_responses;i++) step_responses[i]=reCast<int,IssmDouble>(responses[n*num_responses+i]);
+		femmodel->parameters->SetParam(step_responses,1,num_responses,StepResponsesEnum);
+
+		/*In steady state inversion, compute new temperature field now*/
+		if(solution_type==SteadystateSolutionEnum) solutioncore(femmodel);
+
+		if(VerboseControl()) _printf0_("   compute adjoint state:\n");
+		adjointcore(femmodel);
+		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);
+			goto cleanup_and_return;
+		}
+
+		if(VerboseControl()) _printf0_("   optimizing along gradient direction\n");
+		optpars.maxiter=reCast<int,IssmDouble>(maxiter[n]); optpars.cm_jump=cm_jump[n];
+		BrentSearch(&search_scalar,J+n,&optpars,&objectivefunction,&optargs);
+
+		if(VerboseControl()) _printf0_("   updating parameter using optimized search scalar\n"); //true means update save controls
+		InputControlUpdatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,search_scalar,true);
+
+		if(controlconvergence(J[n],tol_cm)) break;
+	}
+
+	if(VerboseControl()) _printf0_("   preparing final solution\n");
+	femmodel->parameters->SetParam(true,SaveResultsEnum);
+	solutioncore(femmodel);
+
+	/*some results not computed by steadystate_core or diagnostic_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]);
+
+		#ifdef _HAVE_ADOLC_
+		IssmPDouble* J_passive=xNew<IssmPDouble>(nsteps);
+		for(i=0;i<nsteps;i++) J_passive[i]=reCast<IssmPDouble>(J[i]);
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J_passive,nsteps,1,1,0));
+		xDelete<IssmPDouble>(J_passive);
+		#else
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J,nsteps,1,1,0));
+		#endif
+	}
+
+	cleanup_and_return:
+	/*Free ressources: */
+	xDelete<int>(control_type);
+	xDelete<int>(step_responses);
+	xDelete<IssmDouble>(maxiter);
+	xDelete<IssmDouble>(responses);
+	xDelete<IssmDouble>(cm_jump);
+	xDelete<IssmDouble>(J);
+}
+bool controlconvergence(IssmDouble J, IssmDouble tol_cm){
+
+	bool converged=false;
+
+	/*Has convergence been reached?*/
+	if (!xIsNan<IssmDouble>(tol_cm) && J<tol_cm){
+		converged=true;
+		if(VerboseConvergence()) _printf0_("      Convergence criterion reached: J = " << J << " < " << tol_cm);
+	}
+
+	return converged;
+}
Index: /issm/trunk/src/c/analyses/controltao_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/controltao_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/controltao_core.cpp	(revision 15396)
@@ -0,0 +1,189 @@
+/*!\file: control_core.cpp
+ * \brief: core of the control solution 
+ */ 
+#include <config.h>
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+#if defined (_HAVE_TAO_) && defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 1)
+#include <tao.h>
+
+/*Local prototype*/
+int FormFunctionGradient(TaoSolver,Vec,IssmDouble*,Vec,void*);
+int IssmMonitor(TaoSolver,void*);
+typedef struct {
+	FemModel* femmodel;
+	double*   J;
+} AppCtx;
+
+void controltao_core(FemModel* femmodel){
+
+	/*TAO*/
+	int                 ierr;
+	int                 num_controls,solution_type;
+	int                 nsteps,maxiter;
+	AppCtx              user;
+	TaoSolver           tao = 0;
+	IssmDouble         *dummy        = NULL;
+	int                *control_list = NULL;
+	Vector<IssmDouble> *X            = NULL;
+	Vector<IssmDouble> *XL           = NULL;
+	Vector<IssmDouble> *XU           = NULL;
+
+	/*Initialize TAO*/
+	int argc; char **args=NULL;
+	PetscGetArgs(&argc,&args);
+	ierr = TaoInitialize(&argc,&args,(char*)0,"");
+	if(ierr) _error_("Could not initialize Tao");
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&control_list,NULL,InversionControlParametersEnum);
+	femmodel->parameters->FindParam(&nsteps,InversionNstepsEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+	maxiter=nsteps*10;
+
+	/*Prepare Toolkit*/
+	ToolkitsOptionsFromAnalysis(femmodel->parameters,DefaultAnalysisEnum);
+
+	/*Initialize TAO*/
+	TaoCreate(IssmComm::GetComm(),&tao);
+	if(VerboseControl()) _printf0_("   Initializing the Toolkit for Advanced Optimization (TAO)\n");
+	TaoSetFromOptions(tao);
+	TaoSetType(tao,"tao_blmvm");
+	//TaoSetType(tao,"tao_cg");
+	//TaoSetType(tao,"tao_lmvm");
+
+	/*Prepare all TAO parameters*/
+	TaoSetMonitor(tao,IssmMonitor,&user,NULL);
+	TaoSetMaximumFunctionEvaluations(tao,maxiter);
+	TaoSetMaximumIterations(tao,nsteps);
+	TaoSetTolerances(tao,0.,0.,0.,0.,0.);
+
+	GetVectorFromControlInputsx(&X, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	TaoSetInitialVector(tao,X->pvector->vector);
+	TaoSetVariableBounds(tao,XL->pvector->vector,XU->pvector->vector);
+	delete XL;
+	delete XU;
+
+	user.J=xNewZeroInit<double>(maxiter+5);
+	user.femmodel=femmodel;
+	TaoSetObjectiveAndGradientRoutine(tao,FormFunctionGradient,(void*)&user); 
+
+	/*Solver optimization problem*/
+	if(VerboseControl()) _printf0_("   Starting optimization\n");
+	TaoSolve(tao);
+	TaoView(tao,PETSC_VIEWER_STDOUT_WORLD);
+	TaoGetSolutionVector(tao,&X->pvector->vector);
+	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
+	for(int i=0;i<num_controls;i++){
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,control_list[i]);
+	}
+	femmodel->results->AddObject(new GenericExternalResult<double*>(femmodel->results->Size()+1,JEnum,user.J,maxiter+3,1,1,0));
+
+	/*Finalize*/
+	if(VerboseControl()) _printf0_("   preparing final solution\n");
+	femmodel->parameters->SetParam(true,SaveResultsEnum);
+	void (*solutioncore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	solutioncore(femmodel);
+
+	/*Clean up and return*/
+	xDelete<int>(control_list);
+	xDelete<double>(user.J);
+	delete X;
+	TaoDestroy(&tao);
+	TaoFinalize();
+}
+int FormFunctionGradient(TaoSolver tao, Vec Xpetsc, IssmDouble *fcn,Vec G,void *userCtx){
+
+	/*Retreive arguments*/
+	int                  solution_type,num_cost_functions;
+	AppCtx              *user            = (AppCtx *)userCtx;
+	FemModel            *femmodel        = user->femmodel;
+	int                 *cost_functions  = NULL;
+	IssmDouble          *cost_functionsd = NULL;
+	Vector<IssmDouble>  *gradient        = NULL;
+	Vector<IssmDouble>  *X               = NULL;
+
+	/*Convert input to Vec*/
+	X=new Vector<IssmDouble>(Xpetsc);
+
+	/*Set new variable*/
+	//VecView(X,PETSC_VIEWER_STDOUT_WORLD);
+	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
+	delete X;
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&num_cost_functions,InversionNumCostFunctionsEnum);
+	femmodel->parameters->FindParam(&cost_functionsd,NULL,NULL,InversionCostFunctionsEnum);
+
+	/*Prepare objective function*/
+	cost_functions=xNew<int>(num_cost_functions);
+	for(int i=0;i<num_cost_functions;i++) cost_functions[i]=(int)cost_functionsd[i]; //FIXME
+	femmodel->parameters->SetParam(cost_functions,1,num_cost_functions,StepResponsesEnum);
+
+	/*Compute solution and adjoint*/
+	void (*solutioncore)(FemModel*)=NULL;
+	void (*adjointcore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
+	solutioncore(femmodel);
+	adjointcore(femmodel);
+
+	/*Compute objective function*/
+	femmodel->CostFunctionx(fcn);
+
+	/*Compute gradient*/
+	Gradjx(&gradient,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	VecCopy(gradient->pvector->vector,G); delete gradient;
+	VecScale(G,-1.);
+
+	/*Clean-up and return*/
+	xDelete<int>(cost_functions);
+	xDelete<IssmDouble>(cost_functionsd);
+	return 0;
+}
+int IssmMonitor(TaoSolver tao, void *userCtx){
+
+	int       i,its,num_responses;
+	IssmDouble    f,gnorm,cnorm,xdiff;
+	AppCtx   *user      = (AppCtx *)userCtx;
+	FemModel *femmodel  = user->femmodel;
+	Element  *element   = NULL;
+	int      *responses = NULL;
+
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	femmodel->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+
+	TaoGetSolutionStatus(tao, &its, &f, &gnorm, &cnorm, &xdiff, NULL);
+	if(its==0) _printf0_("Iter       Function      Residual  |  List of contributions\n");
+	if(its==0) _printf0_("-----------------------------------+-----------------------\n");
+	_printf0_(setw(4)<<its<<"   "<<setw(12)<<setprecision(7)<<f<<"  "<<setw(12)<<setprecision(7)<<gnorm<<"  | ");
+	user->J[its]=f;
+
+	/*Retrieve objective functions independently*/
+	for(i=0;i<num_responses;i++){
+		femmodel->Responsex(&f,EnumToStringx(responses[i]),i);
+		_printf0_(" "<<setw(12)<<setprecision(7)<<f);
+	}
+	_printf0_("\n");
+
+	/*Clean-up and return*/
+	xDelete<int>(responses);
+	return 0;
+}
+
+#else
+void controltao_core(FemModel* femmodel){
+	_error_("TAO not installed or PETSc version not supported");
+}
+#endif //_HAVE_TAO_ 
Index: /issm/trunk/src/c/analyses/dakota_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/dakota_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/dakota_core.cpp	(revision 15396)
@@ -0,0 +1,229 @@
+/*!\file:  dakota_core.cpp
+ * \brief: wrapper to the Dakota capabilities. qmu fires up Dakota, and registers a Dakota Pluggin
+ * which will be in charge of running the solution sequences repeteadly, to garner statistics. 
+ *
+ * This routine deals with running ISSM and Dakota in library mode. In library mode, Dakota does not 
+ * run as an execuatble. Its capabilities are linked into the ISSM software. ISSM calls dakota routines 
+ * directly from the dakota library. qmu.cpp is the code that is in charge of calling those routines. 
+ *
+ * Dakota has its own way of running in parallel (for embarassingly parallel jobs). We do not want that, 
+ * as ISSM knows exactly how to run "really parallel" jobs that use all CPUS. To bypass Dakota's parallelism, 
+ * we overloaded the constructor for the parallel library (see the Dakota patch in the externalpackages/dakota
+ * directory). This overloaded constructor fires up Dakota serially on CPU 0 only! We take care of broadcasting 
+ * to the other CPUS, hence ISSM is running in parallel, and Dakota serially on CPU0. 
+ *
+ * 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. 
+ * 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 
+ * DakotaSpawnCore. In the end, DakotaSpawnCore is fired up on all CPUS, with CPU0 having Dakota inputs, that it will 
+ * broacast to other CPUS. 
+ *
+ * Now, how does dakota call the DakotaSpawnCore routine? The DakotaSpawnCore is embedded into the DakotaPlugin object 
+ * which is derived from the Direct Interface Dakota objct. This is the only way to run Dakota in library 
+ * mode (see their developper guide for more info). Dakota registers the DakotaPlugin object into its own 
+ * database, and calls on the embedded DakotaSpawnCore from CPU0. 
+ *
+ */ 
+
+/*include files: {{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../shared/shared.h"
+#include "../classes/classes.h"
+
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+#if _DAKOTA_MAJOR_ < 5 || (_DAKOTA_MAJOR_ == 5 && _DAKOTA_MINOR_ < 3)
+#include <ParallelLibrary.H>
+#include <ProblemDescDB.H>
+#include <DakotaStrategy.H>
+#include <DakotaModel.H>
+#include <DakotaInterface.H>
+#else
+#include <ParallelLibrary.hpp>
+#include <ProblemDescDB.hpp>
+#include <DakotaStrategy.hpp>
+#include <DakotaModel.hpp>
+#include <DakotaInterface.hpp>
+#endif
+#include "./DakotaSpawnCore.h"
+#endif
+/*}}}*/
+/*DakotaPlugin class {{{*/
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+#if _DAKOTA_MAJOR_ < 5 || (_DAKOTA_MAJOR_ == 5 && _DAKOTA_MINOR_ < 3)
+#include <DirectApplicInterface.H>
+#include <DakotaResponse.H>
+#include <ParamResponsePair.H>
+#include <system_defs.h>
+#include <ProblemDescDB.H>
+#include <ParallelLibrary.H>
+#else
+#include <DirectApplicInterface.hpp>
+#include <DakotaResponse.hpp>
+#include <ParamResponsePair.hpp>
+#include <ProblemDescDB.hpp>
+#include <ParallelLibrary.hpp>
+#endif
+namespace SIM {
+	class DakotaPlugin: public Dakota::DirectApplicInterface{
+		public:
+			/*these fields are used by core solutions: */
+			void *femmodel;
+			int   counter;
+			/*Constructors/Destructors*/
+			DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* in_femmodel):Dakota::DirectApplicInterface(problem_db){/*{{{*/
+				femmodel = in_femmodel;
+				counter  = 0;
+			}/*}}}*/
+			~DakotaPlugin(){/*{{{*/
+				/* Virtual destructor handles referenceCount at Interface level. */ 
+			}/*}}}*/
+		protected:
+			/*execute the input filter portion of a direct evaluation invocation*/
+			//int derived_map_if(const Dakota::String& if_name);
+			/*execute an analysis code portion of a direct evaluation invocation*/
+			int derived_map_ac(const Dakota::String& driver){/*{{{*/
+
+				int i;
+				IssmDouble* variables=NULL;
+				char** variable_descriptors=NULL;
+				char*  variable_descriptor=NULL;
+				IssmDouble* responses=NULL;
+
+				/*increae counter: */
+				counter++;
+
+				/*Before launching analysis, we need to transfer the dakota inputs into Issm 
+				 *readable variables: */
+
+				/*First, the variables: */
+				variables=xNew<IssmDouble>(numACV);
+				for(i=0;i<numACV;i++){
+					variables[i]=xC[i];
+				}
+				/*The descriptors: */
+				variable_descriptors=xNew<char*>(numACV);
+				for(i=0;i<numACV;i++){
+					std::string label=xCLabels[i];
+					variable_descriptor=xNew<char>(strlen(label.c_str())+1);
+					memcpy(variable_descriptor,label.c_str(),(strlen(label.c_str())+1)*sizeof(char));
+
+					variable_descriptors[i]=variable_descriptor;
+				}
+
+				/*Initialize responses: */
+				responses=xNewZeroInit<IssmDouble>(numFns);
+
+				/*run core solution: */
+				DakotaSpawnCore(responses,numFns, variables,variable_descriptors,numACV,femmodel,counter);
+
+				/*populate responses: */
+				for(i=0;i<numFns;i++){
+					fnVals[i]=responses[i];
+				}
+
+				/*Free ressources:*/
+				xDelete<IssmDouble>(variables);
+				for(i=0;i<numACV;i++){
+					variable_descriptor=variable_descriptors[i];
+					xDelete<char>(variable_descriptor);
+				}
+				xDelete<char*>(variable_descriptors);
+				xDelete<IssmDouble>(responses);
+
+				return 0;
+			}/*}}}*/
+			/*execute the output filter portion of a direct evaluation invocation*/
+			//int derived_map_of(const Dakota::String& of_name);
+			/*add for issm: */
+			int GetCounter(){/*{{{*/
+				return counter;
+			}/*}}}*/
+		private:
+	};
+} 
+#endif
+/*}}}*/
+
+void dakota_core(FemModel* femmodel){ 
+
+	#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+
+	int                my_rank;
+	char              *dakota_input_file  = NULL;
+	char              *dakota_output_file = NULL;
+	char              *dakota_error_file  = NULL;
+	int                status             = 0;
+	Dakota::ModelLIter ml_iter;
+	Parameters        *parameters         = NULL;
+
+	/*Recover dakota_input_file, dakota_output_file and dakota_error_file, in the parameters dataset in parallel */
+	femmodel->parameters->FindParam(&dakota_input_file,QmuInNameEnum);
+	femmodel->parameters->FindParam(&dakota_output_file,QmuOutNameEnum);
+	femmodel->parameters->FindParam(&dakota_error_file,QmuErrNameEnum);
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(my_rank==0){
+
+		// 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. 
+		Dakota::ProblemDescDB problem_db(parallel_lib); 
+
+		// Manage input file parsing, output redirection, and restart processing
+		// without a CommandLineHandler.  This version relies on parsing of an
+		// input file.
+		problem_db.manage_inputs(dakota_input_file);
+		// specify_outputs_restart() is only necessary if specifying non-defaults
+		parallel_lib.specify_outputs_restart(dakota_output_file,dakota_error_file,NULL,NULL);
+
+		// Instantiate the Strategy object (which instantiates all Model and
+		// Iterator objects) using the parsed information in problem_db.
+		Dakota::Strategy selected_strategy(problem_db);
+
+		// convenience function for iterating over models and performing any
+		// interface plug-ins
+		Dakota::ModelList& models = problem_db.model_list();
+
+		for (ml_iter = models.begin(); ml_iter != models.end(); ml_iter++) {
+
+			Dakota::Interface& interface = ml_iter->interface();
+
+			//set DB nodes to the existing Model specification
+			problem_db.set_db_model_nodes(ml_iter->model_id());
+
+			// Serial case: plug in derived Interface object without an analysisComm
+			interface.assign_rep(new SIM::DakotaPlugin(problem_db,(void*)femmodel), false);
+		}
+
+		// Execute the strategy
+		problem_db.lock(); // prevent run-time DB queries
+		selected_strategy.run_strategy();
+
+		//Warn other cpus that we are done running the dakota iterator, by setting the counter to -1:
+		DakotaSpawnCore(NULL,0, NULL,NULL,0,femmodel,-1);
+
+	}
+	else{
+
+		for(;;){
+			if(!DakotaSpawnCore(NULL,0, NULL,NULL,0,femmodel,0))break; //counter came in at -1 on cpu0, bail out.
+		}
+	}
+
+	/*Free ressources:*/
+	xDelete<char>(dakota_input_file);
+	xDelete<char>(dakota_error_file);
+	xDelete<char>(dakota_output_file);
+
+	#endif //#ifdef _HAVE_DAKOTA_
+}
Index: /issm/trunk/src/c/analyses/diagnostic_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/diagnostic_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/diagnostic_core.cpp	(revision 15396)
@@ -0,0 +1,108 @@
+/*!\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/dummy_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/dummy_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/dummy_core.cpp	(revision 15396)
@@ -0,0 +1,11 @@
+/*!\file: dummy_core.cpp
+ * \brief: dummy core (nothing done)
+ */ 
+
+class FemModel;
+
+void dummy_core(FemModel* femmodel){
+
+	/*We do not do anything*/
+
+}
Index: /issm/trunk/src/c/analyses/enthalpy_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/enthalpy_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/enthalpy_core.cpp	(revision 15396)
@@ -0,0 +1,33 @@
+/*!\file: enthalpy_core.cpp
+ * \brief: core of the enthalpy solution 
+ */ 
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../modules/modules.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void enthalpy_core(FemModel* femmodel){
+
+	/*intermediary*/
+	bool   save_results;
+
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("   computing enthalpy\n");
+	femmodel->SetCurrentConfiguration(EnthalpyAnalysisEnum);
+	solutionsequence_nonlinear(femmodel,true);
+
+	/*transfer enthalpy to enthalpy picard for the next step: */
+	InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnthalpyEnum,EnthalpyPicardEnum);
+
+	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);
+	}
+}
Index: /issm/trunk/src/c/analyses/gia_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/gia_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/gia_core.cpp	(revision 15396)
@@ -0,0 +1,57 @@
+/*!\file: gia_core.cpp
+ * \brief: core of the GIA 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 gia_core(FemModel* femmodel){
+
+	int i;
+	Vector<IssmDouble>*  wg  = NULL;
+	Vector<IssmDouble>*  dwdtg  = NULL;
+	IssmDouble*          x   = NULL;
+	IssmDouble*          y   = NULL;
+
+	/*parameters: */
+	bool save_results;
+	int  gsize;
+	int  configuration_type;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	if(VerboseSolution()) _printf0_("   computing GIA\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(GiaAnalysisEnum);
+
+	/*Figure out size of g-set deflection vector and allocate solution vector: */
+	gsize      = femmodel->nodes->NumberOfDofs(configuration_type,GsetEnum);
+	wg = new Vector<IssmDouble>(gsize);
+	dwdtg = new Vector<IssmDouble>(gsize);
+
+	/*first, recover x and y vectors from vertices: */
+	VertexCoordinatesx(&x,&y,NULL,femmodel->vertices); //no need for z coordinate
+
+	/*call the main module: */
+	femmodel->Deflection(wg,dwdtg,x,y);
+
+	/*assemble vector: */
+	wg->Assemble();
+	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);
+
+	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);
+	}
+
+}
Index: /issm/trunk/src/c/analyses/gradient_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/gradient_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/gradient_core.cpp	(revision 15396)
@@ -0,0 +1,48 @@
+/*!\file:  gradient_core.cpp
+ * \brief compute inverse method gradient direction.
+ */ 
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void gradient_core(FemModel* femmodel,int step,bool orthogonalize){ 
+
+	/*Intermediaries*/
+	IssmDouble  norm_inf;
+	IssmDouble *norm_list    = NULL;
+	Vector<IssmDouble>*     new_gradient = NULL;
+	Vector<IssmDouble>*     gradient     = NULL;
+	Vector<IssmDouble>*     old_gradient = NULL;
+
+	/*Compute gradient*/
+	if(VerboseControl()) _printf0_("   compute cost function gradient\n");
+	Gradjx(&gradient,&norm_list,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters);
+
+	if (orthogonalize){
+		if(VerboseControl()) _printf0_("   orthogonalization\n");
+		ControlInputGetGradientx(&old_gradient,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters);
+		Orthx(&new_gradient,gradient,old_gradient); delete old_gradient; delete gradient;
+	}
+	else{ 
+		new_gradient=gradient;
+	}
+
+	/*Check that gradient is clean*/
+	norm_inf=new_gradient->Norm(NORM_INF);
+	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
+	if(xIsNan<IssmDouble>(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
+
+	/*plug back into inputs: */
+	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,new_gradient);
+	delete new_gradient;
+
+	/*Scale Gradients*/
+	ControlInputScaleGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,norm_list,step);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(norm_list);
+}
Index: /issm/trunk/src/c/analyses/hydrology_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/hydrology_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/hydrology_core.cpp	(revision 15396)
@@ -0,0 +1,104 @@
+/*!\file: hydrology_core.cpp
+ * \brief: core of the hydrology 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 hydrology_core(FemModel* femmodel){
+
+	int i;
+
+	/*intermediary*/
+	int        step,nsteps;
+	int        output_frequency,hydrology_model;
+	bool       save_results;
+	bool       modify_loads=true;
+	bool       isefficientlayer;
+	IssmDouble starttime,final_time;
+	IssmDouble time,dt;
+
+	/*first recover parameters common to all solutions*/
+	femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
+	femmodel->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
+	femmodel->parameters->FindParam(&hydrology_model,HydrologyModelEnum);
+
+	/*first compute slopes: */
+	if (hydrology_model==HydrologyshreveEnum){
+		surfaceslope_core(femmodel);
+		bedslope_core(femmodel);
+	}
+
+	/*Compute number of time steps: */
+	if((dt==0)|| (final_time==0)){
+		dt=0;
+		nsteps=1;
+	}
+	else nsteps=reCast<int,IssmDouble>((final_time-starttime)/dt);
+
+	/*initialize: */
+	step=0;
+	time=starttime;
+
+	/*Loop through time: */
+	for(i=0;i<nsteps;i++){
+
+		if(nsteps)if(VerboseSolution()) _printf0_("time step:" << i+1 << "/" << nsteps << "\n");
+		time+=dt;
+		step+=1;
+		femmodel->parameters->SetParam(time,TimeEnum);
+		femmodel->parameters->SetParam(step,StepEnum);
+
+		if (hydrology_model==HydrologyshreveEnum){
+			if(VerboseSolution()) _printf0_("   computing water column\n");
+			femmodel->SetCurrentConfiguration(HydrologyShreveAnalysisEnum);
+			solutionsequence_nonlinear(femmodel,modify_loads);
+
+			/*transfer water column thickness to old water column thickness: */
+
+			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,WatercolumnEnum,WaterColumnOldEnum);
+
+			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);
+
+				/*unload results*/
+				if(VerboseSolution()) _printf0_("   saving temporary results\n");
+				OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
+			}
+		}
+
+		else if (hydrology_model==HydrologydcEnum){
+			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SedimentHeadEnum,SedimentHeadOldEnum);
+			femmodel->parameters->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+			if (isefficientlayer){
+				InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EplHeadEnum,EplHeadOldEnum);
+			}
+
+			if(VerboseSolution()) _printf0_("   computing water head\n");
+			solutionsequence_hydro_nonlinear(femmodel);
+			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);
+				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);
+				}
+				/*unload results*/
+				if(VerboseSolution()) _printf0_("   saving temporary results\n");
+				OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
+			}
+		}
+
+	}
+}
Index: /issm/trunk/src/c/analyses/objectivefunction.cpp
===================================================================
--- /issm/trunk/src/c/analyses/objectivefunction.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/objectivefunction.cpp	(revision 15396)
@@ -0,0 +1,77 @@
+/*!\file:  objectivefunction
+ * \brief  objective function that returns a misfit, for a certain parameter.
+ */ 
+
+/*include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+/*}}}*/
+
+IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs){
+
+	/*output: */
+	IssmDouble J;
+
+	/*parameters: */
+	int        solution_type,analysis_type;
+	bool       isstokes       = false;
+	bool       conserve_loads = true;
+	FemModel  *femmodel       = NULL;
+
+	/*Recover finite element model: */
+	femmodel=optargs->femmodel;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
+	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);
+	}
+	else if (solution_type==BalancethicknessSolutionEnum){
+		femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+	}
+	else if (solution_type==BalancethicknessSoftSolutionEnum){
+		femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+	}
+	else{
+		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
+	}
+
+	/*update parameter according to scalar: */ //false means: do not save control
+	InputControlUpdatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,search_scalar,false);
+
+	/*Run diagnostic with updated inputs: */
+	if (solution_type==SteadystateSolutionEnum){
+		diagnostic_core(femmodel);	//We need a 3D velocity!! (vz is required for the next thermal run)
+	}
+	else if (solution_type==DiagnosticSolutionEnum){
+		solutionsequence_nonlinear(femmodel,conserve_loads); 
+	}
+	else if (solution_type==BalancethicknessSolutionEnum){
+		solutionsequence_linear(femmodel); 
+	}
+	else if (solution_type==BalancethicknessSoftSolutionEnum){
+		/*Don't do anything*/
+	}
+	else{
+		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
+	}
+
+	/*Compute misfit for this velocity field.*/
+	femmodel->CostFunctionx(&J);
+
+	/*Free ressources:*/
+	return J;
+}
Index: /issm/trunk/src/c/analyses/prognostic_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/prognostic_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/prognostic_core.cpp	(revision 15396)
@@ -0,0 +1,58 @@
+/*!\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 15396)
+++ /issm/trunk/src/c/analyses/steadystate_core.cpp	(revision 15396)
@@ -0,0 +1,142 @@
+/*!\file: steadystate_core.cpp
+ * \brief: core of the steadystate solution 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+/*Local prototypes*/
+bool steadystateconvergence(Vector<IssmDouble>* tg,Vector<IssmDouble>* tg_old,Vector<IssmDouble>* ug,Vector<IssmDouble>* ug_old,IssmDouble reltol);
+
+void steadystate_core(FemModel* femmodel){
+
+	/*intermediary: */
+	int step; 
+	Vector<IssmDouble>* ug     = NULL;
+	Vector<IssmDouble>* ug_old = NULL;
+	Vector<IssmDouble>* tg     = NULL;
+	Vector<IssmDouble>* tg_old = NULL;
+
+	/*parameters: */
+	bool        save_results,isenthalpy;
+	int         maxiter;
+	IssmDouble  reltol;
+	int         numoutputs        = 0;
+	int        *requested_outputs = NULL;
+
+	/* recover parameters:*/
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&maxiter,SteadystateMaxiterEnum);
+	femmodel->parameters->FindParam(&numoutputs,SteadystateNumRequestedOutputsEnum);
+	femmodel->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
+	femmodel->parameters->FindParam(&reltol,SteadystateReltolEnum);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,SteadystateRequestedOutputsEnum);
+
+	/*intialize counters: */
+	step=1;
+
+	for(;;){
+
+		if(VerboseSolution()) _printf0_("   computing temperature and velocity for step: " << step << "\n");
+		#ifdef _HAVE_THERMAL_
+		if(isenthalpy==0){
+			thermal_core(femmodel);
+			femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+			GetSolutionFromInputsx(&tg,femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+		}
+		else{
+			enthalpy_core(femmodel);
+			GetSolutionFromInputsx(&tg,femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+		}
+		#else
+		_error_("ISSM was not compiled with thermal capabilities. Exiting");
+		#endif
+
+		if(VerboseSolution()) _printf0_("   computing new velocity\n");
+		diagnostic_core(femmodel);
+		GetSolutionFromInputsx(&ug,femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+
+		if(step>1){
+			if(VerboseSolution()) _printf0_("   checking steadystate convergence\n");
+			if(steadystateconvergence(tg,tg_old,ug,ug_old,reltol)) break;
+		}
+		if(step>maxiter){
+			if(VerboseSolution()) _printf0_("   maximum number steadystate iterations " << maxiter << " reached\n");
+			break;
+		}
+
+		/*update results and increase counter*/
+		delete tg_old;tg_old=tg;
+		delete ug_old;ug_old=ug;
+		step++;
+	}
+
+	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);
+		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
+	}
+
+	/*Free ressources:*/
+	delete tg;
+	delete ug;
+	xDelete<int>(requested_outputs);
+}
+bool steadystateconvergence(Vector<IssmDouble>* tg,Vector<IssmDouble>* tg_old,Vector<IssmDouble>* ug,Vector<IssmDouble>* ug_old,IssmDouble reltol){
+
+	/*Output*/
+	bool converged = true;
+
+	/*Intermediary*/
+	Vector<IssmDouble>* dug    = NULL;
+	Vector<IssmDouble>* dtg    = NULL;
+	IssmDouble          ndt,nt;
+	IssmDouble          ndu,nu;
+
+	/*compute norm(du)/norm(u)*/
+	dug=ug_old->Duplicate(); ug_old->Copy(dug); dug->AYPX(ug,-1.0);
+	ndu=dug->Norm(NORM_TWO); nu=ug_old->Norm(NORM_TWO);
+	if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+	if((ndu/nu)<reltol){
+		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<ndu/nu*100<<" < "<<reltol*100<<" %\n");
+	}
+	else{ 
+		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<ndu/nu*100<<" > "<<reltol*100<<" %\n");
+		converged=false;
+	}
+
+	/*compute norm(dt)/norm(t)*/
+	dtg=tg_old->Duplicate(); tg_old->Copy(dtg); dtg->AYPX(tg,-1.0);
+	ndt=dtg->Norm(NORM_TWO); nt=tg_old->Norm(NORM_TWO);
+	if (xIsNan<IssmDouble>(ndt) || xIsNan<IssmDouble>(nt)) _error_("convergence criterion is NaN!");
+	if((ndt/nt)<reltol){
+		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   Temperature convergence: norm(dt)/norm(t)"<<ndt/nt*100<<" < "<<reltol*100<<" %\n");
+	}
+	else{ 
+		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   Temperature convergence: norm(dt)/norm(t)"<<ndt/nt*100<<" > "<<reltol*100<<" %\n");
+		converged=false;
+	}
+
+	/*clean up and return*/
+	delete dtg;
+	delete dug;
+	return converged;
+}
Index: /issm/trunk/src/c/analyses/surfaceslope_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/surfaceslope_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/surfaceslope_core.cpp	(revision 15396)
@@ -0,0 +1,34 @@
+/*!\file: surfaceslope_core.cpp
+ * \brief: core of the slope solution 
+ */ 
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+void surfaceslope_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("computing slope...\n");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SurfaceSlopeXAnalysisEnum);
+	solutionsequence_linear(femmodel);
+	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SurfaceSlopeYAnalysisEnum);
+	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,SurfaceSlopeXEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceSlopeYEnum);
+	}
+
+}
Index: /issm/trunk/src/c/analyses/thermal_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/thermal_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/thermal_core.cpp	(revision 15396)
@@ -0,0 +1,42 @@
+/*!\file: thermal_core.cpp
+ * \brief: core of the thermal 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 thermal_core(FemModel* femmodel){
+
+	/*intermediary*/
+	bool   save_results;
+	bool   dakota_analysis  = false;
+	int    solution_type;
+
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	if(dakota_analysis && solution_type!=TransientSolutionEnum){
+		femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+		ResetConstraintsx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+
+	if(VerboseSolution()) _printf0_("   computing temperatures\n");
+	femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+	solutionsequence_thermal_nonlinear(femmodel);
+
+	if(VerboseSolution()) _printf0_("   computing melting\n");
+	femmodel->SetCurrentConfiguration(MeltingAnalysisEnum);
+	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,TemperatureEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BasalforcingsMeltingRateEnum);
+	}
+}
Index: /issm/trunk/src/c/analyses/transient_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/transient_core.cpp	(revision 15396)
+++ /issm/trunk/src/c/analyses/transient_core.cpp	(revision 15396)
@@ -0,0 +1,180 @@
+/*!\file: transient_3d_core.cpp
+ * \brief: core of the transient_3d solution 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <float.h>
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void transient_core(FemModel* femmodel){
+
+	/*parameters: */
+	IssmDouble starttime,finaltime,dt,yts;
+	bool   isdiagnostic,isprognostic,isthermal,isgroundingline,isenthalpy,isdelta18o,isgia;
+	bool   save_results,dakota_analysis;
+	bool   time_adapt=false;
+	int    output_frequency;
+	int    dim,groundingline_migration;
+	int    numoutputs         = 0;
+	int    *requested_outputs = NULL;
+
+	/*intermediary: */
+	int    step;
+	IssmDouble time;
+
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
+	femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
+	femmodel->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	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(&isthermal,TransientIsthermalEnum);
+	femmodel->parameters->FindParam(&isgia,TransientIsgiaEnum);
+	femmodel->parameters->FindParam(&isgroundingline,TransientIsgroundinglineEnum);
+	femmodel->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
+	if(isgroundingline) femmodel->parameters->FindParam(&groundingline_migration,GroundinglineMigrationEnum);
+	femmodel->parameters->FindParam(&numoutputs,TransientNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,TransientRequestedOutputsEnum);
+	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+
+	/*initialize: */
+	step=0;
+	time=starttime;
+
+	/*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){
+		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);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuThicknessEnum,ThicknessEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuSurfaceEnum,SurfaceEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuBedEnum,BedEnum);
+		if(dim==2)InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuMaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
+		if(isthermal && dim==3){
+			//Update Vertex Position after updating Thickness and Bed
+			femmodel->SetCurrentConfiguration(PrognosticAnalysisEnum);
+			femmodel->UpdateVertexPositionsx();
+			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVxMeshEnum,VxMeshEnum);
+			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVyMeshEnum,VyMeshEnum);
+			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVzMeshEnum,VzMeshEnum);
+			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuTemperatureEnum,TemperatureEnum);
+			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuMeltingEnum,BasalforcingsMeltingRateEnum);
+			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuMaterialsRheologyBEnum,MaterialsRheologyBEnum);
+			//Reset Thermal Constraints
+			femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+			ResetConstraintsx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		}
+	}
+
+	while(time < finaltime - (yts*DBL_EPSILON)){ //make sure we run up to finaltime.
+
+		/*Increment*/
+		if(time_adapt){
+			femmodel->TimeAdaptx(&dt);
+			if(time+dt>finaltime) dt=finaltime-time;
+			femmodel->parameters->SetParam(dt,TimesteppingTimeStepEnum);
+		}
+		step+=1;
+		time+=dt;
+		femmodel->parameters->SetParam(time,TimeEnum);
+		femmodel->parameters->SetParam(step,StepEnum);
+
+		if(VerboseSolution()) _printf0_("iteration " << step << "/" << floor((finaltime-time)/dt)+step << "  time [yr]: " << time/yts << " (time step: " << dt/yts << ")\n");
+		if(step%output_frequency==0 || time==finaltime)
+		 save_results=true;
+		else
+		 save_results=false;
+		femmodel->parameters->SetParam(save_results,SaveResultsEnum);
+
+		if(isthermal && dim==3){
+			if(VerboseSolution()) _printf0_("   computing temperatures\n");
+			#ifdef _HAVE_THERMAL_
+			if(isenthalpy==0){
+				thermal_core(femmodel);
+			}
+			else{
+				enthalpy_core(femmodel);
+			}
+			#else
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
+			#endif
+		}
+
+		if(isdiagnostic){
+			if(VerboseSolution()) _printf0_("   computing new velocity\n");
+			#ifdef _HAVE_DIAGNOSTIC_
+			diagnostic_core(femmodel);
+			#else
+			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			#endif
+		}
+
+		if(isprognostic){
+			if(VerboseSolution()) _printf0_("   computing new thickness\n");
+			prognostic_core(femmodel);
+			if(VerboseSolution()) _printf0_("   updating vertices positions\n");
+			femmodel->UpdateVertexPositionsx();
+		}
+
+		if(isgroundingline){
+			if(VerboseSolution()) _printf0_("   computing new grounding line position\n");
+			#ifdef _HAVE_GROUNDINGLINE_
+			GroundinglineMigrationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+			#else
+			_error_("ISSM was not compiled with grounding line migration capabilities. Exiting");
+			#endif
+		}
+		if(isgia){
+			if(VerboseSolution()) _printf0_("   computing glacial isostatic adjustment\n");
+			#ifdef _HAVE_GIA_
+			gia_core(femmodel);
+			#else
+			_error_("ISSM was not compiled with gia capabilities. Exiting");
+			#endif
+
+		}
+
+		/*unload results*/
+		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);
+			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);
+			}
+			if(isgroundingline && (groundingline_migration==SubelementMigrationEnum || groundingline_migration==SubelementMigration2Enum)){
+				InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,GLlevelsetEnum);
+			}
+
+			if(VerboseSolution()) _printf0_("   saving temporary results\n");
+			OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
+		}
+	}
+
+	femmodel->RequestedDependentsx();
+
+	/*Free ressources:*/
+	xDelete<int>(requested_outputs);
+}
Index: /issm/trunk/src/c/bamg/AdjacentTriangle.cpp
===================================================================
--- /issm/trunk/src/c/bamg/AdjacentTriangle.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/AdjacentTriangle.cpp	(revision 15396)
@@ -0,0 +1,75 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "AdjacentTriangle.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	//See header file
+
+	/*Methods*/
+	/*FUNCTION AdjacentTriangle::Locked {{{*/
+	int  AdjacentTriangle::Locked() const {
+		return t->AdjEdgeIndex[a] & 4;
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::MarkUnSwap {{{*/
+	int  AdjacentTriangle::MarkUnSwap() const {
+		return t->AdjEdgeIndex[a] & 8;
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::GetAllFlag_UnSwap {{{*/
+	int  AdjacentTriangle::GetAllFlag_UnSwap() const {
+		// take all flag except MarkUnSwap
+		return t->AdjEdgeIndex[a] & 1012;
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::SetLock {{{*/
+	void AdjacentTriangle::SetLock(){
+		t->SetLocked(a);
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::Adj {{{*/
+	AdjacentTriangle AdjacentTriangle::Adj() const {
+		return  t->Adj(a);
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::EdgeVertex {{{*/
+	BamgVertex* AdjacentTriangle::EdgeVertex(const int & i) const {
+		return t->vertices[VerticesOfTriangularEdge[a][i]];
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::OppositeVertex {{{*/
+	BamgVertex* AdjacentTriangle::OppositeVertex() const {
+		return t->vertices[bamg::OppositeVertex[a]]; 
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::det {{{*/
+	Icoor2 & AdjacentTriangle::det() const {
+		return t->det;
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::swap {{{*/
+	int AdjacentTriangle::swap(){
+		return  t->swap(a);
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::SetAdj2 {{{*/
+	void AdjacentTriangle::SetAdj2(const AdjacentTriangle & ta, int l  ){
+		//set Adjacent Triangle of a triangle
+		if(t) {
+			t->adj[a]=ta.t;
+			t->AdjEdgeIndex[a]=ta.a|l;
+		}
+		if(ta.t) {
+			ta.t->adj[ta.a] = t ;
+			ta.t->AdjEdgeIndex[ta.a] = a| l ;
+		}
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/AdjacentTriangle.h
===================================================================
--- /issm/trunk/src/c/bamg/AdjacentTriangle.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/AdjacentTriangle.h	(revision 15396)
@@ -0,0 +1,44 @@
+#ifndef _TRIANGLEADJACENT_H_
+#define _TRIANGLEADJACENT_H_
+
+#include "./include.h"
+#include "./BamgVertex.h"
+
+namespace bamg {
+
+	class Triangle;
+	class Triangle;
+
+	class AdjacentTriangle {
+
+		public:
+			Triangle* t; //pointer toward the triangle
+			int  a;      //Edge number
+
+			//Constructors
+			AdjacentTriangle():a(0),t(NULL) {};
+			AdjacentTriangle(Triangle* tt,int  aa): t(tt),a(aa &3) {};
+
+			//Operators
+			operator Triangle * () const {return t;}
+			operator Triangle & () const {return *t;}
+			operator int() const {return a;}
+			AdjacentTriangle & operator++(){ a= NextEdge[a]; return *this; }
+			AdjacentTriangle operator--(){ a= PreviousEdge[a]; return *this; }
+
+			//Methods
+
+			//Methods
+			int  Locked() const;
+			int  MarkUnSwap() const;
+			int  GetAllFlag_UnSwap() const;
+			void SetLock();
+			void SetAdj2(const AdjacentTriangle &ta, int l=0);
+			int  swap();
+			AdjacentTriangle Adj() const;
+			BamgVertex* EdgeVertex(const int & i) const;
+			BamgVertex* OppositeVertex() const;
+			Icoor2& det() const;
+	};
+}
+#endif
Index: /issm/trunk/src/c/bamg/BamgGeom.cpp
===================================================================
--- /issm/trunk/src/c/bamg/BamgGeom.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/BamgGeom.cpp	(revision 15396)
@@ -0,0 +1,32 @@
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+
+/*Constructors/Destructors*/
+/*FUNCTION BamgGeom::BamgGeom(){{{*/
+BamgGeom::BamgGeom(){
+
+	this->VerticesSize[0]=0,          this->VerticesSize[1]=0;          this->Vertices=NULL;
+	this->EdgesSize[0]=0,             this->EdgesSize[1]=0;             this->Edges=NULL;
+	this->TangentAtEdgesSize[0]=0,    this->TangentAtEdgesSize[1]=0;    this->TangentAtEdges=NULL;
+	this->CornersSize[0]=0,           this->CornersSize[1]=0;           this->Corners=NULL;
+	this->RequiredVerticesSize[0]=0,  this->RequiredVerticesSize[1]=0;  this->RequiredVertices=NULL;
+	this->RequiredEdgesSize[0]=0,     this->RequiredEdgesSize[1]=0;     this->RequiredEdges=NULL;
+	this->CrackedEdgesSize[0]=0,      this->CrackedEdgesSize[1]=0;      this->CrackedEdges=NULL;
+	this->SubDomainsSize[0]=0,        this->SubDomainsSize[1]=0;        this->SubDomains=NULL;
+
+}
+/*}}}*/
+/*FUNCTION BamgGeom::~BamgGeom(){{{*/
+BamgGeom::~BamgGeom(){
+
+	xDelete<double>(this->Vertices);
+	xDelete<double>(this->Edges);
+	xDelete<double>(this->TangentAtEdges);
+	xDelete<double>(this->Corners);
+	xDelete<double>(this->RequiredVertices);
+	xDelete<double>(this->RequiredEdges);
+	xDelete<double>(this->CrackedEdges);
+	xDelete<double>(this->SubDomains);
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/bamg/BamgGeom.h
===================================================================
--- /issm/trunk/src/c/bamg/BamgGeom.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/BamgGeom.h	(revision 15396)
@@ -0,0 +1,31 @@
+/*!\file:  BamgGeom.h
+ */ 
+
+#ifndef _BAMGGEOM_H_
+#define _BAMGGEOM_H_
+
+class BamgGeom{
+
+	public:
+		int     VerticesSize[2];
+		double* Vertices;
+		int     EdgesSize[2];
+		double* Edges;
+		int     TangentAtEdgesSize[2];
+		double* TangentAtEdges;
+		int     CornersSize[2];
+		double* Corners;
+		int     RequiredVerticesSize[2];
+		double* RequiredVertices;
+		int     RequiredEdgesSize[2];
+		double* RequiredEdges;
+		int     CrackedEdgesSize[2];
+		double* CrackedEdges;
+		int     SubDomainsSize[2];
+		double* SubDomains;
+
+		BamgGeom();
+		~BamgGeom();
+};
+
+#endif
Index: /issm/trunk/src/c/bamg/BamgMesh.cpp
===================================================================
--- /issm/trunk/src/c/bamg/BamgMesh.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/BamgMesh.cpp	(revision 15396)
@@ -0,0 +1,54 @@
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+
+/*Constructors/Destructors*/
+/*FUNCTION BamgMesh::BamgMesh(){{{*/
+BamgMesh::BamgMesh(){
+
+	this->VerticesSize[0]=0,                  this->VerticesSize[1]=0;                 this->Vertices=NULL;
+	this->EdgesSize[0]=0,                     this->EdgesSize[1]=0;                    this->Edges=NULL;
+	this->TrianglesSize[0]=0,                 this->TrianglesSize[1]=0;                this->Triangles=NULL;
+	this->QuadrilateralsSize[0]=0,            this->QuadrilateralsSize[1]=0;           this->Quadrilaterals=NULL;
+
+	this->SubDomainsSize[0]=0,                this->SubDomainsSize[1]=0;               this->SubDomains=NULL;
+	this->SubDomainsFromGeomSize[0]=0,        this->SubDomainsFromGeomSize[1]=0;       this->SubDomainsFromGeom=NULL;
+	this->CrackedVerticesSize[0]=0,           this->CrackedVerticesSize[1]=0;          this->CrackedVertices=NULL;
+	this->CrackedEdgesSize[0]=0,              this->CrackedEdgesSize[1]=0;             this->CrackedEdges=NULL;
+
+	this->VerticesOnGeomVertexSize[0]=0,      this->VerticesOnGeomVertexSize[1]=0;     this->VerticesOnGeomVertex=NULL;
+	this->VerticesOnGeomEdgeSize[0]=0,        this->VerticesOnGeomEdgeSize[1]=0;       this->VerticesOnGeomEdge=NULL;
+	this->EdgesOnGeomEdgeSize[0]=0,           this->EdgesOnGeomEdgeSize[1]=0;          this->EdgesOnGeomEdge=NULL;
+
+	this->IssmEdgesSize[0]=0,                 this->IssmEdgesSize[1]=0;                this->IssmEdges=NULL;
+	this->IssmSegmentsSize[0]=0,              this->IssmSegmentsSize[1]=0;             this->IssmSegments=NULL;
+
+	this->ElementConnectivitySize[0]=0,       this->ElementConnectivitySize[1]=0;      this->ElementConnectivity=NULL;
+	this->NodalConnectivitySize[0]=0,         this->NodalConnectivitySize[1]=0;        this->NodalConnectivity=NULL;
+	this->NodalElementConnectivitySize[0]=0,  this->NodalElementConnectivitySize[1]=0; this->NodalElementConnectivity=NULL;
+}
+/*}}}*/
+/*FUNCTION BamgMesh::~BamgMesh(){{{*/
+BamgMesh::~BamgMesh(){
+
+	xDelete<double>(this->Vertices);
+	xDelete<double>(this->Edges);
+	xDelete<double>(this->Triangles);
+	xDelete<double>(this->Quadrilaterals);
+
+	xDelete<double>(this->SubDomains);
+	xDelete<double>(this->SubDomainsFromGeom);
+	xDelete<double>(this->CrackedVertices);
+	xDelete<double>(this->CrackedEdges);
+
+	xDelete<double>(this->VerticesOnGeomVertex);
+	xDelete<double>(this->VerticesOnGeomEdge);
+	xDelete<double>(this->EdgesOnGeomEdge);
+
+	xDelete<double>(this->IssmEdges);
+	xDelete<double>(this->IssmSegments);
+
+	xDelete<double>(this->ElementConnectivity);
+	xDelete<double>(this->NodalConnectivity);
+	xDelete<double>(this->NodalElementConnectivity);
+}
+/*}}}*/
Index: /issm/trunk/src/c/bamg/BamgMesh.h
===================================================================
--- /issm/trunk/src/c/bamg/BamgMesh.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/BamgMesh.h	(revision 15396)
@@ -0,0 +1,52 @@
+/*!\file:  BamgMesh.h
+ */ 
+
+#ifndef _BAMGMESH_H_
+#define _BAMGMESH_H_
+
+class BamgMesh{
+
+	public:
+
+		int     VerticesSize[2];
+		double* Vertices;
+		int     EdgesSize[2];
+		double* Edges;
+		int     TrianglesSize[2];
+		double* Triangles;
+		int     QuadrilateralsSize[2];
+		double* Quadrilaterals;
+
+		int     VerticesOnGeomVertexSize[2];
+		double* VerticesOnGeomVertex;
+		int     VerticesOnGeomEdgeSize[2];
+		double* VerticesOnGeomEdge;
+		int     EdgesOnGeomEdgeSize[2];
+		double* EdgesOnGeomEdge;
+
+		int     SubDomainsSize[2];
+		double* SubDomains;
+		int     SubDomainsFromGeomSize[2];
+		double* SubDomainsFromGeom;
+		int     CrackedVerticesSize[2];
+		double* CrackedVertices;
+		int     CrackedEdgesSize[2];
+		double* CrackedEdges;
+
+		/*Output for ISSM*/
+		int     IssmEdgesSize[2];
+		double* IssmEdges;
+		int     IssmSegmentsSize[2];
+		double* IssmSegments;
+		int     ElementConnectivitySize[2];
+		double* ElementConnectivity;
+		int     NodalConnectivitySize[2];
+		double* NodalConnectivity;
+		int     NodalElementConnectivitySize[2];
+		double* NodalElementConnectivity;
+
+		BamgMesh();
+		~BamgMesh();
+};
+
+#endif
Index: /issm/trunk/src/c/bamg/BamgOpts.cpp
===================================================================
--- /issm/trunk/src/c/bamg/BamgOpts.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/BamgOpts.cpp	(revision 15396)
@@ -0,0 +1,86 @@
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+
+/*Constructors/Destructors*/
+/*FUNCTION BamgOpts::BamgOpts() {{{*/
+BamgOpts::BamgOpts(){
+
+	this->anisomax=0;
+	this->cutoff=0;
+	this->coeff=0;
+	this->errg=0;
+	this->gradation=0;
+	this->Hessiantype=0;
+	this->MaxCornerAngle=0;
+	this->maxnbv=0;
+	this->maxsubdiv=0;
+	this->Metrictype=0;
+	this->nbjacobi=0;
+	this->nbsmooth=0;
+	this->omega=0;
+	this->power=0;
+	this->verbose=0;
+
+	this->Crack=0;
+	this->geometricalmetric=0;
+	this->KeepVertices=0;
+	this->splitcorners=0;
+
+	this->hmin=0;
+	this->hmax=0;
+	this->hminVertices=NULL; this->hminVerticesSize[0]=this->hminVerticesSize[1]=0;
+	this->hmaxVertices=NULL; this->hmaxVerticesSize[0]=this->hmaxVerticesSize[1]=0;
+	this->hVertices=NULL;    this->hVerticesSize[0]=this->hVerticesSize[1]=0;
+	this->metric=NULL;       this->metricSize[0]=this->metricSize[1]=0;
+	this->field=NULL;        this->fieldSize[0]=this->fieldSize[1]=0;
+	this->err=NULL;          this->errSize[0]=this->errSize[1]=0;
+
+}
+/*}}}*/
+/*FUNCTION BamgOpts::~BamgOpts() {{{*/
+BamgOpts::~BamgOpts(){
+
+	xDelete<double>(this->hminVertices);
+	xDelete<double>(this->hmaxVertices);
+	xDelete<double>(this->hVertices);
+	xDelete<double>(this->metric);
+	xDelete<double>(this->field);
+	xDelete<double>(this->err);
+
+}
+/*}}}*/
+
+/*Methods*/
+/*FUNCTION BamgOpts::Check{{{*/
+void BamgOpts::Check(void){
+
+	int i;
+
+	if (this->anisomax<1) _error_("'anisomax' option should be >=1");
+	if (this->coeff==0) _error_("'coeff' should be positive");
+	if (this->errg<0) _error_("'errg' option should be >0");
+	if (this->gradation<1) _error_("'gradation' option should be >=1");
+	if (this->Hessiantype!=0  && this->Hessiantype!=1) _error_("'Hessiantype' supported options are 0 and 1");
+	if (this->maxnbv<3) _error_("'maxnbv' option should be >3");
+	if (this->maxsubdiv<=1) _error_("'maxsubdiv' should be >1");
+	if (this->Metrictype!=0   && this->Metrictype!=1 && this->Metrictype!=2) _error_("'Metrictype' supported options are 0, 1 and 2");
+	if (this->nbjacobi<=0) _error_("'nbjacobi' option should be >0");
+	if (this->nbsmooth<=0) _error_("'nbsmooth' option should be >0");
+
+	if (this->Crack!=0  && this->Crack!=1) _error_("'Crack' supported options are 0 and 1");
+	if (this->KeepVertices!=0 && this->KeepVertices!=1) _error_("'KeepVertices' supported options are 0 and 1");
+	if (this->geometricalmetric!=0  && this->geometricalmetric!=1) _error_("'geometricalmetric' supported options are 0 and 1");
+
+	if (this->hmin<=0) _error_("'hmin' option should be >0");
+	if (this->hmax<=0 || this->hmax<this->hmin) _error_("'hmax' option should be between 0 and hmin=" << this->hmin);
+	if (this->hminVertices && this->hminVerticesSize[1]!=1) _error_("'hminVertices' should be a column");
+	if (this->hmaxVertices && this->hmaxVerticesSize[1]!=1) _error_("'hmaxVertices' should be a column");
+	if (this->hVertices && this->hVerticesSize[1]!=1) _error_("'hVertices' should be a column");
+	if (this->metric && (this->metricSize[1]!=1 && this->metricSize[1]!=3)) _error_("'metric' should have either 1 (iso) or 3 (aniso) columns.");
+	if (this->field){
+		if (this->errSize[0]!=1 || this->errSize[1]!=this->fieldSize[1]) _error_("'err' should be of size " << 1 << " x " << this->fieldSize[1]);
+		for (i=0;i<this->fieldSize[1];i++) {if (this->err[i]<=0) _error_("'err' option should be >0");};
+	}
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/bamg/BamgOpts.h
===================================================================
--- /issm/trunk/src/c/bamg/BamgOpts.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/BamgOpts.h	(revision 15396)
@@ -0,0 +1,57 @@
+/*!\file:  BamgOpts.h
+ * \brief place holder for optimization function arguments
+ */ 
+
+#ifndef _BAMGOPTS_H_
+#define _BAMGOPTS_H_
+
+class BamgOpts{
+
+	public:
+
+		/*Parameters*/
+		double  anisomax;
+		double  cutoff;
+		double  coeff;
+		double  errg;
+		double  gradation;
+		int     Hessiantype;
+		double  MaxCornerAngle;
+		int     maxnbv;
+		double  maxsubdiv;
+		int     Metrictype;
+		int     nbjacobi;
+		int     nbsmooth;
+		double  omega;
+		double  power;
+		int     verbose;
+
+		/*Flags*/
+		int     Crack;
+		int     geometricalmetric;
+		int     KeepVertices;
+		int     splitcorners;
+
+		/*Metric related*/
+		double  hmin;
+		double  hmax;
+		int     hminVerticesSize[2];
+		double* hminVertices;
+		int     hmaxVerticesSize[2];
+		double* hmaxVertices;
+		int     hVerticesSize[2];
+		double* hVertices;
+		int     metricSize[2];
+		double* metric;
+		int     fieldSize[2];
+		double* field;
+		int     errSize[2];
+		double* err;
+
+		BamgOpts();
+		~BamgOpts();
+
+		void Check(void);
+
+};
+#endif
Index: /issm/trunk/src/c/bamg/BamgQuadtree.cpp
===================================================================
--- /issm/trunk/src/c/bamg/BamgQuadtree.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/BamgQuadtree.cpp	(revision 15396)
@@ -0,0 +1,598 @@
+#include <limits.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "./bamgobjects.h"
+#include "../datastructures/datastructures.h"
+
+namespace bamg {
+
+	/*MACROS {{{*/
+	/* 
+	 * 
+	 *    J    j
+	 *    ^    ^
+	 *    |    | +--------+--------+
+	 *    |    | |        |        |
+	 * 1X |    | |   2    |   3    |
+	 *    |    | |        |        |
+	 *    |    | +--------+--------+
+	 *    |    | |        |        |
+	 * 0X |    | |   0    |   1    |
+	 *    |    | |        |        |
+	 *    |    | +--------+--------+
+	 *    |    +-----------------------> i
+	 *    |         
+	 *    |----------------------------> I
+	 *              X0        X1  
+	 *
+	 * box 0 -> I=0 J=0 IJ=00  = 0
+	 * box 1 -> I=1 J=0 IJ=01  = 1
+	 * box 2 -> I=0 J=1 IJ=10  = 2
+	 * box 3 -> I=1 J=1 IJ=11  = 3
+	 */
+#define INTER_SEG(a,b,x,y) (((y) > (a)) && ((x) <(b)))
+#define ABS(i) ((i)<0 ?-(i) :(i))
+#define MAX1(i,j) ((i)>(j) ?(i) :(j))
+#define NORM(i1,j1,i2,j2) MAX1(ABS((i1)-(j1)),ABS((i2)-(j2)))
+
+	//IJ(i,j,l) returns the box number of i and j with respect to l
+	//if !j&l and !i&l -> 0 (box zero: lower left )
+	//if !j&l and  i&l -> 1 (box one:  lower right)
+	//if  j&l and !i&l -> 2 (box two:  upper left )
+	//if  j&l and  i&l -> 3 (box three:upper right)
+#define IJ(i,j,l)  ((j&l) ? ((i&l) ? 3:2 ) :((i&l) ? 1:0 ))
+
+	//I_IJ(k,l) returns l if first  bit of k is 1, else 0
+#define I_IJ(k,l)  ((k&1) ? l:0)
+	//J_IJ(k,l) returns l if second bit of k is 1, else 0
+#define J_IJ(k,l)  ((k&2) ? l:0)
+	/*}}}*/
+	/*DOCUMENTATION What is a BamgQuadtree? {{{
+	 * A Quadtree is a very simple way to group vertices according
+	 * to their locations. A square that holds all the points of the mesh
+	 * (or the geometry) is divided into 4 boxes. As soon as one box
+	 * hold more than 4 vertices, it is divided into 4 new boxes, etc...
+	 * There cannot be more than MAXDEEP (=30) subdivision.
+	 * This process is like a Dichotomy in dimension 2
+	 *
+	 *  + - -  -    - -    -    - - + -   - + - + - + - -     - - +
+	 *  |                           |       |   | X |             |
+	 *                                      + - + - +
+	 *  |                           |       |   |   |             |
+	 *                              + -   - + - + - +             +
+	 *  |                           |       |       |             |
+	 *                         
+	 *  |                           |       |       |             |
+	 *  + - -  -    - -    -    - - + -   - + -   - + - -     - - +
+	 *  |                           |               |             |
+	 *                         
+	 *  |                           |               |             |
+	 *                         
+	 *  |                           |               |             |
+	 *  |                           |               |             |
+	 *  + - -  -    - -    -    - - + -   -   -   - + - -     - - +
+	 *  |                           |                             |
+	 *                         
+	 *  |                           |                             |
+	 *                         
+	 *  |                           |                             |
+	 *                         
+	 *  |                           |                             |
+	 *  |                           |                             |
+	 *  |                           |                             |
+	 *  |                           |                             |
+	 *  |                           |                             |
+	 *  + - -  -    - -    -    - - + -   -   -   -   - -     - - +
+	 *
+	 * The coordinate system used in a quadtree are integers to avoid
+	 * round-off errors. The vertex in the lower left box has the coordinates
+	 * (0 0) 
+	 * The upper right vertex has the follwing coordinates:
+	 * 2^30 -1           2^30 -1        in decimal
+	 * 0 1 1 1 .... 1    0 1 1 1 .... 1 in binary
+	 *  \--   29  --/     \--   29  --/
+	 * Using binaries is therefore very easy to locate a vertex in a box:
+	 * we just need to look at the bits from the left to the right (See ::Add)
+	 }}}*/
+
+	/*Constructors/Destructors*/
+	/*FUNCTION BamgQuadtree::BamgQuadtree(){{{*/
+	BamgQuadtree::BamgQuadtree(){
+
+		/*Number of boxes and vertices*/
+		NbBamgQuadtreeBox=0;
+		NbVertices=0;
+
+		/*Create container*/
+		boxcontainer=new DataSet();
+
+		/*Create Root, pointer toward the main box*/
+		root=NewBamgQuadtreeBox();
+
+		}
+	/*}}}*/
+	/*FUNCTION BamgQuadtree::BamgQuadtree(Mesh * t,long nbv){{{*/
+	BamgQuadtree::BamgQuadtree(Mesh * t,long nbv){ 
+
+		/*Number of boxes and vertices*/
+		NbBamgQuadtreeBox=0;
+		NbVertices=0;
+
+		/*Create container*/
+		boxcontainer=new DataSet();
+
+		/*Create Root, pointer toward the main box*/
+		root=NewBamgQuadtreeBox();
+
+		/*Check Sizes*/
+		_assert_(MaxISize>MaxICoor);
+
+		/*Add all vertices of the mesh*/
+		if (nbv==-1) nbv=t->nbv;
+		for (int i=0;i<nbv;i++) Add(t->vertices[i]);
+
+	}
+	/*}}}*/
+	/*FUNCTION BamgQuadtree::~BamgQuadtree(){{{*/
+	BamgQuadtree::~BamgQuadtree() {
+		delete boxcontainer;
+		root=NULL;
+	}
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION BamgQuadtree::Add{{{*/
+	void  BamgQuadtree::Add(BamgVertex &w){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/Add)*/
+		BamgQuadtreeBox** pb=NULL;
+		BamgQuadtreeBox*  b=NULL;
+
+		/*Get integer coodinate of current point w*/
+		register long i=w.i.x, j=w.i.y;
+
+		/*Initialize level*/
+		register long level=MaxISize;
+
+		/*Get inital box (the largest)*/
+		pb = &root;
+
+		/*Find the smallest box where w is located*/
+		while((b=*pb) && (b->nbitems<0)){ 
+
+			//shift b->nbitems by -1
+			b->nbitems--;
+
+			//shifted righ by one bit: level=00000010 -> 00000001
+			level >>= 1;
+
+			//Get next subbox according to the bit value (level)
+			pb = &b->b[IJ(i,j,level)];
+		}
+
+		/*OK, we have found b, a Subbox holding vertices (might be full)
+		  check that the vertex is not already in the box*/
+		if (b){      
+			if (b->nbitems > 3 &&  b->v[3] == &w) return;
+			if (b->nbitems > 2 &&  b->v[2] == &w) return;
+			if (b->nbitems > 1 &&  b->v[1] == &w) return;
+			if (b->nbitems > 0 &&  b->v[0] == &w) return;
+		}
+
+		/*check that l is not 0 (this should not happen as MaxDepth = 30)*/
+		_assert_(level>0);
+
+		/*Now, try to add the vertex, if the subbox is full (nbitems=4), we have to divide it
+		  in 4 new subboxes*/
+		while ((b= *pb) && (b->nbitems == 4)){ // the BamgQuadtreeBox is full
+
+			/*Copy the 4 vertices in the current BamgQuadtreebox*/
+			BamgVertex* v4[4];
+			v4[0]= b->v[0];
+			v4[1]= b->v[1];
+			v4[2]= b->v[2];
+			v4[3]= b->v[3];
+
+			/*set nbitems as negative 
+			 * (box full -> holds 4 pointers toward subboxes and not 4 vertices)*/
+			b->nbitems = -b->nbitems;
+
+			/*Initialize the 4 pointers toward the 4 subboxes*/
+			b->b[0]=b->b[1]=b->b[2]=b->b[3]=NULL;
+
+			/*level = 0010000 -> 0001000*/
+			level >>= 1;
+
+			/*Put the four vertices in the new boxes*/
+			for (int k=0;k<4;k++){
+
+				int          ij;
+				/*bb is the new "sub"box of b where v4[k] is located*/
+				BamgQuadtreeBox *bb = b->b[ij=IJ(v4[k]->i.x,v4[k]->i.y,level)];
+
+				// alloc the BamgQuadtreeBox
+				if (!bb) bb=b->b[ij]=NewBamgQuadtreeBox(); 
+
+				/*Copy the current vertex*/
+				bb->v[bb->nbitems++] = v4[k];
+			}
+
+			/*Get the subbox where w (i,j) is located*/
+			pb = &b->b[IJ(i,j,level)];
+		}
+
+		/*alloc the BamgQuadtreeBox if necessary*/
+		if (!(b=*pb)) b=*pb= NewBamgQuadtreeBox();
+
+		/*Add w*/
+		b->v[b->nbitems++]=&w;
+
+		//Increase NbVertices by one (we have one new vertex)
+		NbVertices++;
+	}
+	/*}}}*/
+	/*FUNCTION BamgQuadtree::NearestVertex{{{*/
+	BamgVertex*  BamgQuadtree::NearestVertex(Icoor1 i,Icoor1 j) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/NearestVertex)*/
+
+		/*Intermediaries*/
+		BamgQuadtreeBox *pb[MaxDepth];
+		int          pi[MaxDepth];
+		Icoor1       ii[MaxDepth];
+		Icoor1       jj[MaxDepth];
+		int          level;
+		long         n0;
+		BamgQuadtreeBox *b;
+		long         h0;
+		long         h = MaxISize;
+		long         hb= MaxISize;
+		Icoor1       i0=0,j0=0;
+
+		/*initial output as NULL (no vertex found)*/
+		BamgVertex*  nearest_v=NULL;
+
+		/*Project w coordinates (i,j) onto [0,MaxISize-1] x [0,MaxISize-1] -> (iplus,jplus)*/
+		Icoor1 iplus( i<MaxISize ? (i<0?0:i) : MaxISize-1);
+		Icoor1 jplus( j<MaxISize ? (j<0?0:j) : MaxISize-1);
+
+		/*Get initial Quadtree box (largest)*/
+		b = root;
+
+		/*if the tree is empty, return NULL pointer*/
+		if (!root->nbitems) return nearest_v; 
+
+		/*else, find the smallest non-empty BamgQuadtreeBox containing  the point (i,j)*/
+		while((n0=b->nbitems)<0){
+
+			Icoor1       hb2 = hb >> 1;             //size of the current box
+			int          k   = IJ(iplus,jplus,hb2); //box number (0,1,2 or 3)
+			BamgQuadtreeBox *b0  = b->b[k];             //pointer toward current box
+
+			/* break if NULL box or empty (Keep previous box b)*/
+			if (( b0 == NULL) || (b0->nbitems == 0)) break;
+
+			/*Get next Quadtree box*/
+			b=b0;	
+			i0 += I_IJ(k,hb2); // i orign of BamgQuadtreeBox (macro)
+			j0 += J_IJ(k,hb2); // j orign of BamgQuadtreeBox 
+			hb = hb2;          // size of the box (in Int)
+		}
+
+		/*The box b, is the smallest box containing the point (i,j) and
+		 * has the following properties:
+		 * - n0: number of items (>0 if vertices, else boxes)
+		 * - hb: box size (int)
+		 * - i0: x coordinate of the lower left corner
+		 * - j0: y coordinate of the lower left corner*/
+
+		/* if the current subbox is holding vertices, we are almost done*/
+		if (n0>0){  
+			//loop over the vertices of the box and find the closest vertex
+			for(int k=0;k<n0;k++){
+
+				/*get integer coordinates of current vertex*/
+				I2 i2=b->v[k]->i;
+
+				/*Compute norm with w*/
+				h0=NORM(iplus,i2.x,jplus,i2.y);
+
+				/*is it smaller than previous value*/
+				if (h0<h){
+					h = h0;
+					nearest_v = b->v[k];
+				}
+			}
+			/*return closest vertex*/
+			return nearest_v;
+		}
+
+		/* general case: the current box is empty, we have to go backwards
+			and find the closest not-empty box and find the closest vertex*/
+
+		/*Initialize search variables*/
+		pb[0]=b;                             //pointer toward the box b
+		pi[0]=b->nbitems>0?(int)b->nbitems:4;//number of boxes in b
+		ii[0]=i0;                            //i coordinate of the box lowest left corner
+		jj[0]=j0;                            //j coordinate of the box lowest left corner
+
+		/*initialize h: smallest box size, containing a vertex close to w*/
+		h=hb;
+
+		/*Main loop*/
+		level=0;
+		do {
+
+			/*get current box*/
+			b= pb[level];
+
+			/*Loop over the items in current box (if not empty!)*/
+			while (pi[level]){
+
+				/*We are looping now over the items of b. k is the current index (in [0 3])*/
+				pi[level]--;
+				int k=pi[level];
+
+				/*if the current subbox is holding vertices (b->nbitems<0 is subboxes)*/
+				if (b->nbitems>0){
+					I2 i2=b->v[k]->i;
+					h0 = NORM(iplus,i2.x,jplus,i2.y);
+					if (h0<h){
+						h=h0;
+						nearest_v=b->v[k];
+					}
+				}
+				/*else: current box b is pointing toward 4 boxes
+				 * test sub-box k and go deeper into the tree if it is non empty
+				 * and contains the point w modulo a size h that is either the size of the smallest
+				 * non empty box containing w, or the closest point to w (so far) */
+				else{
+					BamgQuadtreeBox* b0=b;
+
+					/*if the next box exists:*/
+					if (b=b->b[k]){
+
+						/*Get size (hb) and coordinates of the current sub-box lowest left corner*/
+						hb>>=1;
+						Icoor1 iii = ii[level]+I_IJ(k,hb);
+						Icoor1 jjj = jj[level]+J_IJ(k,hb);
+
+						/*if the current point (iplus,jplus) is in b (modulo h), this box is good:
+						 * it is holding vertices that are close to w */
+						if (INTER_SEG(iii,iii+hb,iplus-h,iplus+h) && INTER_SEG(jjj,jjj+hb,jplus-h,jplus+h)){
+							level++;
+							pb[level]= b;
+							pi[level]= b->nbitems>0 ?(int)  b->nbitems : 4  ;
+							ii[level]= iii;
+							jj[level]= jjj;
+						}
+
+						//else go backwards
+						else{
+							//shifted righ by one bit: hb=001000000 -> 01000000
+							b=b0;
+							hb<<=1;
+						}
+					}
+					else{
+						/*Current box is NULL, go to next subbox of b (k=k-1)*/
+						b=b0;
+					}
+				}
+			}
+
+			/*We have found a vertex, now, let's try the other boxes of the previous level
+			 * in case there is a vertex closest to w that has not yet been tested*/
+			hb <<= 1;
+		} while (level--);
+
+		/*return nearest_v, nearest vertex*/
+		return nearest_v;
+
+	}
+	/*}}}*/
+	/*FUNCTION BamgQuadtree::NearestVertexWithNormal{{{*/
+	BamgVertex*  BamgQuadtree::NearestVertexWithNormal(Icoor1 i,Icoor1 j) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/NearestVertexWithNormal)*/
+
+		BamgQuadtreeBox * pb[ MaxDepth ];
+		int  pi[ MaxDepth  ];
+		Icoor1 ii[  MaxDepth ], jj [ MaxDepth];
+		int l; // level
+		BamgQuadtreeBox * b;
+		long     h =MaxISize,h0;
+		long     hb=MaxISize;
+		Icoor1  i0=0,j0=0;
+		Icoor1  iplus( i<MaxISize?(i<0?0:i):MaxISize-1);
+		Icoor1  jplus( j<MaxISize?(j<0?0:j):MaxISize-1);
+
+		BamgVertex *vn=0;
+
+		// init for optimisation ---
+		b = root;
+		register long  n0;
+		if (!root->nbitems)
+		 return vn; // empty tree 
+
+		while( (n0 = b->nbitems) < 0) 
+		  {
+			// search the non empty 
+			// BamgQuadtreeBox containing  the point (i,j)
+			register Icoor1 hb2 = hb >> 1 ;
+			register  int k = IJ(iplus,jplus,hb2);// BamgQuadtreeBox number of size hb2 contening i;j
+			register BamgQuadtreeBox * b0= b->b[k];
+			if ( ( b0 == 0) || (b0->nbitems == 0) ) 
+			 break; // null box or empty   => break 	    
+			b=b0;	
+			i0 += I_IJ(k,hb2); // i orign of BamgQuadtreeBox
+			j0 += J_IJ(k,hb2); // j orign of BamgQuadtreeBox 
+			hb = hb2; 
+		  }
+
+		if ( n0 > 0) 
+		  {  
+			for(register int k=0;k<n0;k++)
+			  {
+				I2 i2 =  b->v[k]->i;
+				//   try if is in the right direction -- 
+				h0 = NORM(iplus,i2.x,jplus,i2.y);
+				if (h0 <h) {
+					h = h0;
+					vn = b->v[k];}
+			  }
+			if (vn) return vn; 
+		  }
+		// general case -----
+		// INITIALISATION OF THE HEAP 
+		l =0; // level 
+		pb[0]= b;
+		pi[0]=b->nbitems>0 ?(int)  b->nbitems : 4  ;
+		ii[0]=i0;
+		jj[0]=j0;
+		h=hb;
+		do {   // walk on the tree  
+			b= pb[l];
+			while (pi[l]--) // loop on 4 element of the box
+			  { 	      
+				int k = pi[l];
+
+				if (b->nbitems>0) // BamgVertex BamgQuadtreeBox none empty
+				  { 
+					I2 i2 =  b->v[k]->i;
+					// if good direction when try -- 
+
+					h0 = NORM(iplus,i2.x,jplus,i2.y);
+					if (h0 <h) 
+					  {
+						h = h0;
+						vn = b->v[k];
+					  }
+				  }
+				else // Pointer BamgQuadtreeBox 
+				  { 
+					register BamgQuadtreeBox *b0=b;
+					if ((b=b->b[k])) 
+					  {
+						hb >>=1 ; // div by 2
+						register Icoor1 iii = ii[l]+I_IJ(k,hb);
+						register Icoor1 jjj = jj[l]+J_IJ(k,hb);
+
+						if  (INTER_SEG(iii,iii+hb,iplus-h,iplus+h) && INTER_SEG(jjj,jjj+hb,jplus-h,jplus+h)) 
+						  {
+							pb[++l]=  b;
+							pi[l]= b->nbitems>0 ?(int)  b->nbitems : 4  ;
+							ii[l]= iii;
+							jj[l]= jjj;
+
+						  }
+						else
+						 b=b0, hb <<=1 ;
+					  }
+					else
+					 b=b0;
+				  }
+			  }
+			hb <<= 1; // mul by 2 
+		} while (l--);
+
+		return vn;
+	}
+	/*}}}*/
+	/*FUNCTION BamgQuadtree::NewBamgQuadtreeBox {{{*/
+	BamgQuadtree::BamgQuadtreeBox* BamgQuadtree::NewBamgQuadtreeBox(void){
+
+		/*Output*/
+		BamgQuadtreeBox* newbox=NULL;
+
+		/*Create and initialize a new box*/
+		newbox=new BamgQuadtreeBox;
+		newbox->nbitems=0;
+		newbox->b[0]=NULL;
+		newbox->b[1]=NULL;
+		newbox->b[2]=NULL;
+		newbox->b[3]=NULL;
+
+		/*Add root to the container*/
+		boxcontainer->AddObject(newbox);
+
+		/*Increase counter*/
+		NbBamgQuadtreeBox++;
+
+		/*currentbox now points toward next quadtree box*/
+		return newbox;
+	}/*}}}*/
+	/*FUNCTION BamgQuadtree::ToClose {{{*/
+	BamgVertex*   BamgQuadtree::ToClose(BamgVertex & v,double seuil,Icoor1 hx,Icoor1 hy){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.cpp/ToClose)*/
+
+		const Icoor1 i=v.i.x;
+		const Icoor1 j=v.i.y;
+		const R2 X(v.r);
+		const Metric  Mx(v.m);
+
+		BamgQuadtreeBox * pb[ MaxDepth ];
+		int  pi[ MaxDepth  ];
+		Icoor1 ii[  MaxDepth ], jj [ MaxDepth];
+		register int l=0; // level
+		register BamgQuadtreeBox * b;
+		Icoor1 h=MaxISize;
+		Icoor1 hb =  MaxISize;
+		Icoor1 i0=0,j0=0;
+
+		//  BamgVertex *vn=0;
+
+		if (!root->nbitems)
+		 return 0; // empty tree 
+
+		// general case -----
+		pb[0]=root;
+		pi[0]=root->nbitems>0 ?(int)  root->nbitems : 4  ;
+		ii[0]=i0;
+		jj[0]=j0;
+		h=hb;
+		do {    
+			b= pb[l];
+			while (pi[l]--){ 	      
+				register int k = pi[l];
+
+				if (b->nbitems>0){ // BamgVertex BamgQuadtreeBox none empty
+					I2 i2 =  b->v[k]->i;
+					if ( ABS(i-i2.x) <hx && ABS(j-i2.y) <hy )
+					  {
+						R2 XY(X,b->v[k]->r);
+						double dd;
+						if( (dd= LengthInterpole(Mx(XY), b->v[k]->m(XY)))  < seuil ){
+							return b->v[k]; 
+						}
+					  }
+				}
+				else{ // Pointer BamgQuadtreeBox 
+					register BamgQuadtreeBox *b0=b;
+					if ((b=b->b[k])){
+						hb >>=1 ; // div by 2
+						register long iii = ii[l]+I_IJ(k,hb);
+						register long jjj = jj[l]+J_IJ(k,hb);
+
+						if  (INTER_SEG(iii,iii+hb,i-hx,i+hx) && INTER_SEG(jjj,jjj+hb,j-hy,j+hy)){
+							pb[++l]=  b;
+							pi[l]= b->nbitems>0 ?(int)  b->nbitems : 4  ;
+							ii[l]= iii;
+							jj[l]= jjj;
+
+						}
+						else{
+							b=b0;
+							hb <<=1 ;
+						}
+					}
+					else{
+						b=b0;
+					}
+				}
+			}
+			hb <<= 1; // mul by 2 
+		} while (l--);
+
+		return 0;
+	}
+	/*}}}*/
+}
Index: /issm/trunk/src/c/bamg/BamgQuadtree.h
===================================================================
--- /issm/trunk/src/c/bamg/BamgQuadtree.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/BamgQuadtree.h	(revision 15396)
@@ -0,0 +1,60 @@
+/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.h)*/
+#ifndef _BAMGQUADTREE_H
+#define _BAMGQUADTREE_H
+
+#include "./include.h"
+#include "../datastructures/datastructures.h"
+
+namespace bamg {
+
+	const int  MaxDepth = 30;
+	const long MaxISize = ( 1L << MaxDepth);  // = 2^30 : 010000000000..000 (bitwise operation)
+
+	class BamgVertex;
+
+	class BamgQuadtree{
+
+		private:
+
+			/*A quadtree box contains a maximum of 4 vertices. 4 other quadtree boxes are
+			 * created if a fifth vertex is added to the same box. A Quadtree box is therefore
+			 * composed of EITHER:
+			 * - up to 4 vertices
+			 * - 4 "sub" quadtree boxes*/
+			class BamgQuadtreeBox: public Object{ 
+				public:
+					int nbitems; // number of current vertices in the box
+					union{
+						BamgQuadtreeBox* b[4];
+						BamgVertex*  v[4];
+					};
+					/*Object functions*/
+					void    Echo()       {_error_("not implemented yet"); };
+					void    DeepEcho()   {_error_("not implemented yet"); };
+					int     Id()         {_error_("not implemented yet"); };
+					int     ObjectEnum() {_error_("not implemented yet"); };
+					Object *copy()       {_error_("not implemented yet"); };
+			};
+
+			/*BamgQuadtree private Fields*/
+			DataSet* boxcontainer;
+
+		public:
+
+			/*BamgQuadtree public Fields*/
+			BamgQuadtreeBox* root;
+			long         NbBamgQuadtreeBox;
+			long         NbVertices;
+
+			BamgQuadtree();
+			BamgQuadtree(Mesh *t,long nbv=-1);
+			~BamgQuadtree();
+
+			BamgVertex      *NearestVertex(Icoor1 i,Icoor1 j);
+			BamgVertex      *NearestVertexWithNormal(Icoor1  i,Icoor1 j);
+			BamgQuadtreeBox *NewBamgQuadtreeBox(void);
+			BamgVertex      *ToClose(BamgVertex &,double ,Icoor1,Icoor1);
+			void             Add(BamgVertex &w);
+	};
+}
+#endif
Index: /issm/trunk/src/c/bamg/BamgVertex.cpp
===================================================================
--- /issm/trunk/src/c/bamg/BamgVertex.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/BamgVertex.cpp	(revision 15396)
@@ -0,0 +1,258 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+#include "./det.h"
+
+namespace bamg {
+
+	/*Methods*/
+	/*FUNCTION BamgVertex::Echo {{{*/
+
+	void BamgVertex::Echo(void){
+
+		_printf_("Vertex:\n");
+		_printf_("  integer   coordinates i.x: " << i.x << ", i.y: " << i.y << "\n");
+		_printf_("  Euclidean coordinates r.x: " << r.x << ", r.y: " << r.y << "\n");
+		_printf_("  ReferenceNumber = " << ReferenceNumber << "\n");
+		m.Echo();
+
+		return;
+	}
+	/*}}}*/
+	/*FUNCTION BamgVertex::GetReferenceNumber{{{*/
+	int  BamgVertex::GetReferenceNumber() const { 
+		return ReferenceNumber;
+	}
+	/*}}}*/
+	/*FUNCTION BamgVertex::MetricFromHessian{{{*/
+	void BamgVertex::MetricFromHessian(const double Hxx,const double Hyx, const double Hyy,const double smin,const double smax,const double s,double err,BamgOpts* bamgopts){
+		/*Compute Metric from Hessian*/
+
+		/*get options*/
+		double power=(bamgopts->power);
+		double anisomax=(bamgopts->anisomax);
+		double CutOff=bamgopts->cutoff;
+		double hmin=(bamgopts->hmin);
+		double hmax=(bamgopts->hmax);
+		double coef=bamgopts->coeff;
+		int    Metrictype=(bamgopts->Metrictype);
+
+		/*Intermediary*/
+		double ci;
+
+		/*compute multiplicative coefficient depending on Metric Type (2/9 because it is 2d)*/
+
+		//Absolute Error
+		/*
+		 *            2         1       
+		 *Metric M = ---  ------------   Abs(Hessian)
+		 *            9   err * coeff^2  
+		 */
+		if (Metrictype==0){
+			ci= 2.0/9.0 * 1/(err*coef*coef);
+		}
+
+		//Relative Error
+		/*
+		 *            2         1            Abs(Hessian)
+		 *Metric M = ---  ------------  ----------------------
+		 *            9   err * coeff^2  max( |s| , cutoff*max(|s|) )
+		 *
+		 */
+		else if (Metrictype==1){
+			ci= 2.0/9.0 * 1/(err*coef*coef) * 1/Max( Abs(s), CutOff*(Max(Abs(smin),Abs(smax))));
+		}
+
+		//Rescaled absolute error
+		/*
+		 *            2         1            Abs(Hessian)
+		 *Metric M = ---  ------------  ---------------------- 
+		 *            9   err * coeff^2       (smax-smin)
+		 */
+		else if (Metrictype==2){
+			ci= 2.0/9.0 * 1/(err*coef*coef) * 1/(smax-smin);
+		}
+		else{
+			_error_("Metrictype " << Metrictype << " not supported yet (use 0,1 or 2(default))");
+		}
+
+		//initialize metric Miv with ci*H
+		Metric Miv(Hxx*ci,Hyx*ci,Hyy*ci);
+
+		//Get eigen values and vectors of Miv
+		EigenMetric Vp(Miv);
+
+		//move eigen valuse to their absolute values
+		Vp.Abs();
+
+		//Apply a power if requested by user
+		if(power!=1.0) Vp.pow(power);
+
+		//modify eigen values according to hmin and hmax
+		Vp.Maxh(hmax);
+		Vp.Minh(hmin);
+
+		//Bound anisotropy by 1/(anisomax)^2
+		Vp.BoundAniso2(1/(anisomax*anisomax));
+
+		//rebuild Metric from Vp
+		Metric MVp(Vp);
+
+		//Apply Metric to vertex
+		m.IntersectWith(MVp);
+
+	}
+	/*}}}*/
+	/*FUNCTION BamgVertex::Optim {{{*/
+	long BamgVertex::Optim(int i,int koption){ 
+		long ret=0;
+		if ( t && (IndexInTriangle >= 0 ) && (IndexInTriangle <3) ){
+			ret = t->Optim(IndexInTriangle,koption);
+			if(!i){
+				t =0; // for no future optime 
+				IndexInTriangle= 0;
+			}
+		}
+		return ret;
+	}
+	/*}}}*/
+	/*FUNCTION BamgVertex::Smoothing{{{*/
+	double  BamgVertex::Smoothing(Mesh &Th,const Mesh &BTh,Triangle* &tstart ,double omega){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Smoothing)*/
+
+		register BamgVertex* s=this;
+		BamgVertex &vP = *s,vPsave=vP;
+
+		register Triangle* tbegin= t , *tria = t , *ttc;
+
+		register int k=0,kk=0,j = EdgesVertexTriangle[IndexInTriangle][0],jc;
+		R2 P(s->r),PNew(0,0);
+		do {
+			k++; 
+
+			if (!tria->Hidden(j)){
+				BamgVertex &vQ = (*tria)[VerticesOfTriangularEdge[j][0]]; 
+
+				R2 Q = vQ,QP(P-Q);
+				double lQP = LengthInterpole(vP,vQ,QP);
+				PNew += Q+QP/Max(lQP,1e-20);
+				kk ++;
+			}
+			ttc =  tria->TriangleAdj(j);
+			jc = NextEdge[tria->NuEdgeTriangleAdj(j)];
+			tria = ttc;
+			j = NextEdge[jc];
+			if (k>=2000){
+				_error_("k>=2000 (Maximum number of iterations reached)");
+			}
+		} while ( tbegin != tria); 
+		if (kk<4) return 0;
+		PNew = PNew/(double)kk;
+		R2 Xmove((PNew-P)*omega);
+		PNew = P+Xmove;
+		double delta=Norme2_2(Xmove); 
+
+		Icoor2 deta[3];
+		I2 IBTh  = BTh.R2ToI2(PNew);
+
+		tstart=BTh.TriangleFindFromCoord(IBTh,deta,tstart);  
+
+		if (tstart->det <0){ // outside
+			double ba,bb;
+			AdjacentTriangle edge= CloseBoundaryEdge(IBTh,tstart,ba,bb) ;
+			tstart = edge;
+			vP.m= Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1));
+		}
+		else { // inside
+			double   aa[3];
+			double s = deta[0]+deta[1]+deta[2];
+			aa[0]=deta[0]/s;
+			aa[1]=deta[1]/s;
+			aa[2]=deta[2]/s;
+			vP.m = Metric(aa,(*tstart)[0],(*tstart)[1],(*tstart)[2]);
+		}
+
+		// recompute the det of the triangle
+		vP.r = PNew;
+
+		vP.i = Th.R2ToI2(PNew);
+
+		BamgVertex vPnew = vP;
+
+		int ok=1;
+		int loop=1;
+		k=0;
+		while (ok){
+			ok =0;
+			do {
+				k++; 
+				double detold = tria->det;
+				tria->det =  bamg::det( (*tria)[0],(*tria)[1]  ,(*tria)[2]);
+				if (loop) {
+					BamgVertex *v0,*v1,*v2,*v3;
+					if (tria->det<0) ok =1;			       
+					else if (tria->Quadrangle(v0,v1,v2,v3))
+					  {
+						vP = vPsave;
+						double qold =QuadQuality(*v0,*v1,*v2,*v3);
+						vP = vPnew;
+						double qnew =QuadQuality(*v0,*v1,*v2,*v3);
+						if (qnew<qold) ok = 1;
+					  }
+					else if ( (double)tria->det < detold/2 ) ok=1;
+
+				}
+				tria->SetUnMarkUnSwap(0);
+				tria->SetUnMarkUnSwap(1);
+				tria->SetUnMarkUnSwap(2);
+				ttc =  tria->TriangleAdj(j);
+				jc = NextEdge[tria->NuEdgeTriangleAdj(j)];
+				tria = ttc;
+				j = NextEdge[jc];
+				if (k>=2000){
+					_error_("k>=2000");
+				}
+			}while ( tbegin != tria); 
+
+			if (ok && loop) vP=vPsave; // no move 
+			loop=0;
+		}
+		return delta;
+	}
+	/*}}}*/
+
+	/*Intermediary*/
+	/*FUNCTION QuadQuality{{{*/
+	double QuadQuality(const BamgVertex & a,const BamgVertex &b,const BamgVertex &c,const BamgVertex &d) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/QuadQuality)*/
+
+		// calcul de 4 angles --
+		R2 A((R2)a),B((R2)b),C((R2)c),D((R2)d);
+		R2 AB(B-A),BC(C-B),CD(D-C),DA(A-D);
+		//  Move(A),Line(B),Line(C),Line(D),Line(A);
+		const Metric & Ma  = a;
+		const Metric & Mb  = b;
+		const Metric & Mc  = c;
+		const Metric & Md  = d;
+
+		double lAB=Norme2(AB);
+		double lBC=Norme2(BC);
+		double lCD=Norme2(CD);
+		double lDA=Norme2(DA);
+		AB /= lAB;  BC /= lBC;  CD /= lCD;  DA /= lDA;
+		// version aniso 
+		double cosDAB= Ma(DA,AB)/(Ma(DA)*Ma(AB)),sinDAB= Det(DA,AB);
+		double cosABC= Mb(AB,BC)/(Mb(AB)*Mb(BC)),sinABC= Det(AB,BC);
+		double cosBCD= Mc(BC,CD)/(Mc(BC)*Mc(CD)),sinBCD= Det(BC,CD);
+		double cosCDA= Md(CD,DA)/(Md(CD)*Md(DA)),sinCDA= Det(CD,DA);
+		double sinmin=Min(Min(sinDAB,sinABC),Min(sinBCD,sinCDA));
+		if (sinmin<=0) return sinmin;
+		return 1.0-Max(Max(Abs(cosDAB),Abs(cosABC)),Max(Abs(cosBCD),Abs(cosCDA)));
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/BamgVertex.h
===================================================================
--- /issm/trunk/src/c/bamg/BamgVertex.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/BamgVertex.h	(revision 15396)
@@ -0,0 +1,57 @@
+#ifndef _BAMGVERTEX_H_
+#define _BAMGVERTEX_H_
+
+#include "./include.h"
+#include "./Metric.h"
+#include "./Direction.h"
+#include "./BamgOpts.h"
+
+namespace bamg {
+
+	class Triangle;
+	class Mesh;
+	class VertexOnGeom;
+	class VertexOnEdge;
+
+	class BamgVertex {
+
+		public:
+
+			/*Fields*/
+			I2        i;                 // integer coordinates
+			R2        r;                 // real coordinates
+			Metric    m;
+			long      ReferenceNumber;
+			Direction DirOfSearch;
+			short     IndexInTriangle;              // the vertex number in triangle; varies between 0 and 2 in t
+
+			union {
+				Triangle     *t;                      // one triangle which is containing the vertex
+				long          color;
+				BamgVertex   *MeshVertexHook;         // used in geometry BamgVertex to know the Mesh Vertex associated
+				VertexOnGeom *GeomEdgeHook;    // if IndexInTriangle == 8; // set with Mesh::SetVertexFieldOn()
+				BamgVertex   *BackgroundVertexHook;   // if IndexInTriangle == 16 on Background vertex Mesh::SetVertexFieldOnBTh()
+				VertexOnEdge *BackgroundEdgeHook;     // if IndexInTriangle == 32 on Background edge
+			};
+
+			/*Operators*/
+			operator I2() const {return i;}             // Cast operator
+			operator const R2 & () const {return r;}    // Cast operator
+			operator Metric () const {return m;}        // Cast operator
+			double operator()(R2 x) const { return m(x);} // Get x in the metric m
+
+			/*methods (No constructor and no destructors...)*/
+			double Smoothing(Mesh & ,const Mesh & ,Triangle  * & ,double =1);
+			void   MetricFromHessian(const double Hxx,const double Hyx, const double Hyy, const double smin,const double smax,const double s,const double err,BamgOpts* bamgopts);
+			void   Echo();
+			int    GetReferenceNumber() const;
+			long   Optim(int =1,int =0); 
+
+			//inline functions
+			inline void Set(const BamgVertex &rec,const Mesh & ,Mesh & ){*this=rec;}
+	};
+
+	//Intermediary
+	double QuadQuality(const BamgVertex &,const BamgVertex &,const BamgVertex &,const BamgVertex &);
+}
+#endif
Index: /issm/trunk/src/c/bamg/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/bamg/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/bamg/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,31 @@
+# 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: /issm/trunk/src/c/bamg/CrackedEdge.cpp
===================================================================
--- /issm/trunk/src/c/bamg/CrackedEdge.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/CrackedEdge.cpp	(revision 15396)
@@ -0,0 +1,33 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "CrackedEdge.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION CrackedEdge() {{{*/
+	CrackedEdge::CrackedEdge() {
+		a=NULL;
+		b=NULL;
+		E=NULL;
+		e1=NULL;
+		e2=NULL;
+		indexa[0]=-1;
+		indexa[1]=-1;
+		indexa[2]=-1;
+		indexb[0]=-1;
+		indexb[1]=-1;
+		indexb[2]=-1;
+		length=0;
+		normal.x=0;
+		normal.y=0;
+
+	}
+	/*}}}*/
+
+	/*Methods*/
+
+} 
Index: /issm/trunk/src/c/bamg/CrackedEdge.h
===================================================================
--- /issm/trunk/src/c/bamg/CrackedEdge.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/CrackedEdge.h	(revision 15396)
@@ -0,0 +1,30 @@
+#ifndef _CRACKEDEDGE_H_
+#define _CRACKEDEDGE_H_
+
+#include "./typedefs.h"
+
+namespace bamg {
+
+	class Triangle;
+	class GeomEdge;
+	class Edge;
+
+	class CrackedEdge {
+
+		public:
+			Triangle* a;
+			Triangle* b; 
+			GeomEdge* E;
+			Edge* e1;
+			Edge* e2;
+			double length;
+			R2     normal;
+			long   indexa[3];
+			long   indexb[3];
+
+			//Constructors
+			CrackedEdge();
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/Curve.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Curve.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/Curve.cpp	(revision 15396)
@@ -0,0 +1,37 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Curve.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Curve::Curve(){{{*/
+	Curve::Curve(){
+		FirstEdge=NULL;
+		LastEdge=NULL;
+		FirstVertexIndex=0;
+		LastVertexIndex=0;
+	} 
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Curve::Reverse {{{*/
+	void Curve::Reverse() {
+		/*reverse the direction of the curve */
+		Exchange(FirstEdge,LastEdge);
+		Exchange(FirstVertexIndex,LastVertexIndex);
+	}
+	/*}}}*/
+	/*FUNCTION Curve::Set {{{*/
+	void Curve::Set(const Curve & rec,const Geometry & Gh ,Geometry & GhNew){
+		*this = rec;
+		FirstEdge = GhNew.edges + Gh.GetId(FirstEdge);    
+		LastEdge = GhNew.edges + Gh.GetId(LastEdge); 
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/Curve.h
===================================================================
--- /issm/trunk/src/c/bamg/Curve.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/Curve.h	(revision 15396)
@@ -0,0 +1,26 @@
+#ifndef _CURVE_H_
+#define _CURVE_H_
+
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	class GeomEdge;
+	class Curve;
+	class Geometry;
+
+	class Curve {
+		public:
+			GeomEdge *FirstEdge; //First edge of the curve
+			GeomEdge *LastEdge;  //Last edge of the curve
+			int FirstVertexIndex;       //Last vertex index in the last edge
+			int LastVertexIndex;        //First Vertex index in the first edge
+
+			//Methods
+			Curve();
+			void Reverse(void);
+			void Set(const Curve & rec,const Geometry & Th ,Geometry & ThNew);
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/Direction.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Direction.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/Direction.cpp	(revision 15396)
@@ -0,0 +1,36 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Direction.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Direction() {{{*/
+	Direction::Direction():
+		dir(MaxICoor){
+
+	}/*}}}*/
+	/*FUNCTION Direction(Icoor1 i,Icoor1 j) {{{*/
+	Direction::Direction(Icoor1 i,Icoor1 j) {
+		Icoor2 n2 = 2*(Abs(i)+Abs(j));  
+		Icoor2 r  = MaxICoor* (Icoor2) i;
+		Icoor1 r1 = (Icoor1) (2*(r/ n2)); // odd number 
+		dir = (j>0) ? r1 : r1+1;          // odd-> j>0 even-> j<0
+	}/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Direction::direction{{{*/
+	int Direction::direction(Icoor1 i,Icoor1 j) {
+		int r =1; 
+		if (dir!= MaxICoor) {
+			Icoor2 x(dir/2),y1(MaxICoor/2-Abs(x)),y(dir%2?-y1:y1);
+			r = (x*i + y*j) >=0;
+		}
+		return r;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/Direction.h
===================================================================
--- /issm/trunk/src/c/bamg/Direction.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/Direction.h	(revision 15396)
@@ -0,0 +1,20 @@
+#ifndef _DIRECTION_H_
+#define _DIRECTION_H_
+
+#include "./include.h"
+#include "../shared/Bamg/shared.h"
+
+namespace bamg {
+
+	class Direction {
+		private:
+			Icoor1 dir;
+
+		public:
+			//Methods
+			Direction();
+			Direction(Icoor1 i,Icoor1 j);
+			int direction(Icoor1 i,Icoor1 j);
+	};
+}
+#endif
Index: /issm/trunk/src/c/bamg/DoubleAndInt.h
===================================================================
--- /issm/trunk/src/c/bamg/DoubleAndInt.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/DoubleAndInt.h	(revision 15396)
@@ -0,0 +1,19 @@
+#ifndef _DOUBLEANDINT_H_
+#define _DOUBLEANDINT_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class DoubleAndInt {
+		//class used by Mesh::MakeQuadrangles
+
+		public:
+			double q;
+			long i3j;
+
+			//Operators
+			int operator<(DoubleAndInt a){return q > a.q;}
+	};
+}
+#endif
Index: /issm/trunk/src/c/bamg/Edge.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Edge.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/Edge.cpp	(revision 15396)
@@ -0,0 +1,55 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Edge.h"
+#include "Mesh.h"
+#include "Geometry.h"
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	/*FUNCTION Edge::Set {{{*/
+	void Edge::Set(const Mesh & Th ,long i,Mesh & ThNew){ 
+		*this = Th.edges[i];
+		v[0] = ThNew.vertices + Th.GetId(v[0]);    
+		v[1] = ThNew.vertices + Th.GetId(v[1]);
+		if (GeomEdgeHook) 
+		 GeomEdgeHook =  ThNew.Gh.edges+Th.Gh.GetId(GeomEdgeHook);
+		if (adj[0]) adj[0] =   ThNew.edges +   Th.GetId(adj[0]);
+		if (adj[1]) adj[1] =   ThNew.edges +   Th.GetId(adj[1]);
+	}
+	/*}}}*/
+	/*FUNCTION Edge::Echo {{{*/
+	void Edge::Echo(void){ 
+		_printf_("Edge:\n");
+		_printf_("   pointers towards two vertices: " << v[0] << " " << v[1] << "\n");
+		_printf_("   ReferenceNumber = " << ReferenceNumber << "\n");
+		_printf_("   GeomEdgeHook = " << GeomEdgeHook << "\n");
+		_printf_("   two adjacent edges on the same curve: " << adj[0] << " " << adj[1] << "\n");
+	}
+	/*}}}*/
+	/*FUNCTION Edge::Renumbering{{{*/
+	void Edge::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){
+
+		if (v[0] >=vb && v[0] <ve) v[0] = vb + renu[v[0]-vb];
+		if (v[1] >=vb && v[1] <ve) v[1] = vb + renu[v[1]-vb];
+
+	}
+	/*}}}*/
+	/*FUNCTION Edge::Intersection{{{*/
+	int Edge::Intersection(const  Edge & e){ 
+
+		/*some shecks*/
+		if (!(adj[0]==&e || adj[1]==&e)){ _error_("Intersection bug"); }
+		_assert_(adj[0]==&e || adj[1]==&e);
+
+		return adj[0]==&e?0:1;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/Edge.h
===================================================================
--- /issm/trunk/src/c/bamg/Edge.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/Edge.h	(revision 15396)
@@ -0,0 +1,34 @@
+#ifndef _EDGE_H_
+#define _EDGE_H_
+
+#include "./BamgVertex.h"
+#include "../shared/shared.h"
+#include "./GeomEdge.h"
+
+namespace bamg {
+
+	class Mesh;
+
+	class Edge {
+
+		public:
+			BamgVertex      *v[2];
+			long             ReferenceNumber;
+			GeomEdge *GeomEdgeHook;
+			Edge            *adj[2];       // the 2 adj edges if on the same curve
+
+			//Operators
+			BamgVertex       &operator[](int i){return *v[i];   };
+			BamgVertex       *operator()(int     i){return v[i];};
+			R2                operator()(double  t) const;// return the point
+			const BamgVertex &operator[](int i) const{return *v[i];};
+
+			//Methods
+			void Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu);
+			int  Intersection(const  Edge & e);
+			void Set(const Mesh &,long,Mesh &);
+			void Echo(void);
+
+	};
+}
+#endif
Index: /issm/trunk/src/c/bamg/EigenMetric.cpp
===================================================================
--- /issm/trunk/src/c/bamg/EigenMetric.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/EigenMetric.cpp	(revision 15396)
@@ -0,0 +1,168 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Metric.h"
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	/*Constructor*/
+	/*FUNCTION EigenMetric::EigenMetric(const Metric M){{{*/
+	EigenMetric::EigenMetric(const Metric& M){
+		/*From a metric (a11,a21,a22), get eigen values lambda1 and lambda2 and one eigen vector v*/
+
+		/*Intermediaries*/
+		double a11=M.a11,a21=M.a21,a22=M.a22;
+		double normM;
+		double delta,b;
+
+		/*To get the eigen values, we must solve the following equation:
+		 *     | a11 - lambda    a21        |
+		 * det |                            | = 0
+		 *     | a21             a22-lambda |
+		 *
+		 * We have to solve the following polynom:
+		 *  lamda^2 + ( -a11 -a22)*lambda + (a11*a22-a21*a21) = 0*/
+
+		/*Compute polynom determinant*/
+		b=-a11-a22;
+		delta=b*b - 4*(a11*a22-a21*a21);
+
+		/*Compute norm of M to avoid round off errors*/
+		normM=a11*a11 + a22*a22 + a21*a21;
+
+		/*1: normM too small: eigen values = 0*/
+		if(normM<1.e-30){
+			lambda1=0;
+			lambda2=0;
+			v.x=1;
+			v.y=0;
+		}
+		/*2: delta is small -> double root*/
+		else if (delta < 1.e-5*normM){
+			lambda1=-b/2;
+			lambda2=-b/2;
+			v.x=1;
+			v.y=0;
+		}
+		/*3: general case -> two roots*/
+		else{
+			delta     = sqrt(delta);
+			lambda1   = (-b-delta)/2.0;
+			lambda2   = (-b+delta)/2.0;
+
+			/*Now, one must find the eigen vectors. For that we use the following property of the inner product
+			 *    <Ax,y> = <x,tAy>
+			 * Here, M'(M-lambda*Id) is symmetrical, which gives:
+			 *    ∀(x,y)∈R²xR² <M'x,y> = <M'y,x>
+			 * And we have the following:
+			 *    if y∈Ker(M'), ∀x∈R² <M'x,y> = <x,M'y> = 0
+			 * We have shown that
+			 *    Im(M') ⊥ Ker(M')
+			 *
+			 * To find the eigen vectors of M, we only have to find two vectors
+			 * of the image of M' and take their perpendicular as long as they are
+			 * not 0.
+			 * To do that, we take the images (1,0) and (0,1):
+			 *  x1 = (a11 - lambda)      x2 = a21
+			 *  y1 = a21                 y2 = (a22-lambda)
+			 *
+			 * We take the vector that has the larger norm and take its perpendicular.*/
+
+			double norm1 = (a11-lambda1)*(a11-lambda1) + a21*a21; 
+			double norm2 = a21*a21 + (a22-lambda1)*(a22-lambda1);
+
+			if (norm2<norm1){
+				norm1=sqrt(norm1);
+				v.x = - a21/norm1;
+				v.y = (a11-lambda1)/norm1;
+			}
+			else{
+				norm2=sqrt(norm2);
+				v.x = - (a22-lambda1)/norm2;
+				v.y = a21/norm2;
+			}
+		}
+
+	}
+	/*}}}*/
+	/*FUNCTION EigenMetric::EigenMetric(double r1,double r2,const D2 vp1){{{*/
+	EigenMetric::EigenMetric(double r1,double r2,const D2& vp1): lambda1(r1),lambda2(r2),v(vp1){
+
+	}/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION EigenMetric::Abs{{{*/
+	void   EigenMetric::Abs(){
+		lambda1=bamg::Abs(lambda1),lambda2=bamg::Abs(lambda2);
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Aniso{{{*/
+	double EigenMetric::Aniso() const  { 
+		return sqrt( Aniso2());
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Aniso2{{{*/
+	double EigenMetric::Aniso2() const  { 
+		return lmax()/lmin();
+	}/*}}}*/
+	/*FUNCTION EigenMetric::BoundAniso{{{*/
+	void   EigenMetric::BoundAniso(const double c){ 
+		BoundAniso2(1/(c*c));
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Echo {{{*/
+	void EigenMetric::Echo(void){
+
+		_printf_("EigenMetric:\n");
+		_printf_("   lambda1: " << lambda1 << "\n");
+		_printf_("   lambda2: " << lambda2 << "\n");
+		_printf_("   v.x: " << v.x << "\n");
+		_printf_("   v.y: " << v.y << "\n");
+
+		return;
+	}
+	/*}}}*/
+	/*FUNCTION EigenMetric::hmin{{{*/
+	double EigenMetric::hmin() const {
+		return sqrt(1/bamg::Max3(lambda1,lambda2,1e-30));
+	}/*}}}*/
+	/*FUNCTION EigenMetric::hmax{{{*/
+	double EigenMetric::hmax() const {
+		return sqrt(1/bamg::Max(bamg::Min(lambda1,lambda2),1e-30));
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Isotrope{{{*/
+	void   EigenMetric::Isotrope() {
+		lambda1=lambda2=bamg::Max(lambda1,lambda2);
+	}/*}}}*/
+	/*FUNCTION EigenMetric::lmax{{{*/
+	double EigenMetric::lmax() const {
+		return bamg::Max3(lambda1,lambda2,1e-30);
+	}/*}}}*/
+	/*FUNCTION EigenMetric::lmin{{{*/
+	double EigenMetric::lmin() const {
+		return bamg::Max(bamg::Min(lambda1,lambda2),1e-30);
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Min{{{*/
+	void   EigenMetric::Min(double a) { 
+		lambda1=bamg::Min(a,lambda1); lambda2=bamg::Min(a,lambda2) ;
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Max{{{*/
+	void   EigenMetric::Max(double a) { 
+		//change eigen values
+		lambda1=bamg::Max(a,lambda1); lambda2=bamg::Max(a,lambda2) ;
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Minh{{{*/
+	void   EigenMetric::Minh(double h) {
+		Min(1.0/(h*h));
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Maxh{{{*/
+	void   EigenMetric::Maxh(double h) {
+		//Call Max function
+		Max(1.0/(h*h));
+	}/*}}}*/
+	/*FUNCTION EigenMetric::pow{{{*/
+	void   EigenMetric::pow(double p){
+		lambda1=::pow(lambda1,p);lambda2=::pow(lambda2,p);
+	}/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/GeomEdge.cpp
===================================================================
--- /issm/trunk/src/c/bamg/GeomEdge.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/GeomEdge.cpp	(revision 15396)
@@ -0,0 +1,189 @@
+#include <cstdio>
+#include <string.h>
+#include <cmath>
+
+#include "../shared/shared.h"
+
+#include "GeomEdge.h"
+#include "Geometry.h"
+
+using namespace std;
+
+namespace bamg {
+
+	/*Constructor/Destructor*/
+
+	/*Methods*/
+	/*FUNCTION GeomEdge::Cracked{{{*/
+	int    GeomEdge::Cracked() const  {
+		return type &1;  
+	}/*}}}*/
+	/*FUNCTION GeomEdge::F{{{*/
+	R2 GeomEdge::F(double theta) const{
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/F)*/
+		// parametrization of the curve edge
+
+	   R2 A=v[0]->r,B=v[1]->r;
+		double ca,cb,cta,ctb;
+
+		//Check that theta is in [0 1]
+		_assert_(theta>-1e-12 && theta<1+1e-12);
+
+		if (TgA()){ 
+			if (TgB()){ //Hermite interpolation
+				cb =  theta*theta*(3-2*theta);
+				ca =  1-cb;     
+				cta = (1-theta)*(1-theta)*theta;
+				ctb = (theta-1)*theta*theta ;
+			}
+			else {
+				double t = theta;
+				cb = t*t;
+				ca = 1-cb;
+				cta= t-cb;
+				ctb=0;    
+			}
+		}
+		else{
+			if (TgB()){
+				double t = 1-theta;
+				ca = t*t;
+				cb = 1-ca;
+				ctb= -t+ca;
+				cta=0;    
+			}
+			else { // lagrange P1
+				ca =(1-theta);
+				cb = theta;
+				cta=ctb=0;
+			}
+		}
+		return A*ca + B*cb + tg[0]*cta + tg[1]*ctb;
+	  }
+	/*}}}*/
+	/*FUNCTION GeomEdge::Mark{{{*/
+	int    GeomEdge::Mark()    const  {
+		return type &16; 
+	}/*}}}*/
+	/*FUNCTION GeomEdge::R1tg{{{*/
+	double GeomEdge::R1tg(double theta,R2 & t) const{
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/R1tg)*/
+		// 1/R of radius of cuvature
+
+		R2 A=v[0]->r,B=v[1]->r;
+		double dca,dcb,dcta,dctb;
+		double ddca,ddcb,ddcta,ddctb;
+		double tt = theta*theta;
+
+		//check theta
+		_assert_(theta>=0 && theta<=1);
+
+		if (TgA()){ 
+			if (TgB()){
+				// Tangent A and B provided:
+				// interpolation d'hermite
+				dcb = 6*theta*(1-theta);
+				ddcb = 6*(1-2*theta);
+				dca = -dcb;
+				ddca = -ddcb;
+				dcta =  (3*theta - 4)*theta + 1;
+				ddcta=6*theta-4;
+				dctb = 3*tt - 2*theta;
+				ddctb = 6*theta-2;
+			}
+			else {
+				//Tangent A provided but tangent B not provided
+				// 1-t*t, t-t*t, t*t
+				double t = theta;
+				dcb = 2*t;
+				ddcb = 2;
+				dca = -dcb;
+				ddca = -2;
+				dcta = 1-dcb;
+				ddcta = -ddcb;
+				dctb=0;    
+				ddctb=0;    
+			}
+		}
+		else{
+			if (TgB()){
+				//Tangent B provided but tangent A not provided
+				double t = 1-theta;
+				dca = -2*t;
+				ddca = 2;
+				dcb = -dca;
+				ddcb = -2;
+				dctb = 1+dca;
+				ddctb= ddca;
+				dcta =0;
+				ddcta =0;
+			}
+			else {
+				//Neither thangent A nor tangent B provided
+				// lagrange P1
+				t=B-A;
+				return 0;
+			} 
+		}
+		R2 d  =  A*dca  + B*dcb  + tg[0]* dcta  + tg[1] * dctb;
+		R2 dd =  A*ddca + B*ddcb + tg[0]* ddcta + tg[1] * ddctb;
+		double d2=(d,d);
+		double sd2 = sqrt(d2);
+		t=d;
+		if(d2>1.0e-20){
+			t/=sd2;
+			return Abs(Det(d,dd))/(d2*sd2);
+		}
+		else return 0;
+	}
+	/*}}}*/
+	/*FUNCTION GeomEdge::Required{{{*/
+	int    GeomEdge::Required()       {
+		return type &64; 
+	}/*}}}*/
+	/*FUNCTION GeomEdge::Set {{{*/
+	void GeomEdge::Set(const GeomEdge & rec,const Geometry & Gh ,Geometry & GhNew){ 
+		*this = rec;
+		v[0] = GhNew.vertices + Gh.GetId(v[0]);    
+		v[1] = GhNew.vertices + Gh.GetId(v[1]); 
+		if (Adj[0]) Adj[0] =  GhNew.edges + Gh.GetId(Adj[0]);     
+		if (Adj[1]) Adj[1] =  GhNew.edges + Gh.GetId(Adj[1]);     
+	}
+	/*}}}*/
+	/*FUNCTION GeomEdge::SetCracked{{{*/
+	void   GeomEdge::SetCracked()     { 
+		type |= 1;/*=>1st digit to 1*/
+	}/*}}}*/
+	/*FUNCTION GeomEdge::SetTgA{{{*/
+	void   GeomEdge::SetTgA()         { 
+		type |=4; /*=>2d digit to 1*/
+	}/*}}}*/
+	/*FUNCTION GeomEdge::SetTgB{{{*/
+	void   GeomEdge::SetTgB()         { 
+		type |=8; /*=> 3d digit to 1*/
+	}/*}}}*/
+	/*FUNCTION GeomEdge::SetMark{{{*/
+	void   GeomEdge::SetMark()        { 
+		type |=16;/*=> 4th digiy to 1*/
+	}/*}}}*/
+	/*FUNCTION GeomEdge::SetUnMark{{{*/
+	void   GeomEdge::SetUnMark()      { 
+		type &= 1007 /* 1023-16 = 000111110111 => 4th digit to 0*/;
+	}/*}}}*/
+	/*FUNCTION GeomEdge::SetRequired{{{*/
+	void   GeomEdge::SetRequired()    { 
+		type |= 64;/*=>6th digit to 1*/ 
+	}/*}}}*/
+	  /*FUNCTION GeomEdge::Tg{{{*/
+	int    GeomEdge::Tg(int i) const  {
+		return i==0 ? TgA() : TgB();
+	}/*}}}*/
+	/*FUNCTION GeomEdge::TgA{{{*/
+	int    GeomEdge::TgA()     const  {
+		return type &4;  
+	}/*}}}*/
+	/*FUNCTION GeomEdge::TgB{{{*/
+	int    GeomEdge::TgB()     const  {
+		return type &8;  
+	}/*}}}*/
+}
Index: /issm/trunk/src/c/bamg/GeomEdge.h
===================================================================
--- /issm/trunk/src/c/bamg/GeomEdge.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/GeomEdge.h	(revision 15396)
@@ -0,0 +1,46 @@
+#ifndef _GEOMETRICALEDGE_H_
+#define _GEOMETRICALEDGE_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class GeomVertex;
+	class Geometry;
+
+	class GeomEdge {
+
+		public:
+			GeomVertex *v[2];
+			long               ReferenceNumber;
+			long               CurveNumber;
+			R2                 tg[2];              // the 2 tangentes (tg[0] =0 => no continuity)
+			GeomEdge   *Adj[2];
+			int                AdjVertexIndex[2]; // for a given vertex, this gives the index of the vertex in the adjacent edge (0 or 1)
+			int                type;
+
+			//Operators
+			GeomVertex       & operator[](int i){return *v[i];};
+			const GeomVertex & operator[](int i) const { return *v[i];};
+			GeomVertex       * operator()(int i){return v[i];};  
+
+			//Methods
+			R2     F(double theta) const ; // parametrization of the curve edge
+			double R1tg(double theta,R2 &t) const ; // 1/radius of curvature + tangente
+			int    Tg(int i) const;
+			int    Cracked() const;
+			int    TgA()     const;
+			int    TgB()     const;
+			int    Mark()    const;
+			int    Required();
+			void   SetCracked();
+			void   SetTgA();
+			void   SetTgB();
+			void   SetMark();
+			void   SetUnMark();
+			void   SetRequired();
+			void   Set(const GeomEdge & rec,const Geometry & Th ,Geometry & ThNew);
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/GeomSubDomain.cpp
===================================================================
--- /issm/trunk/src/c/bamg/GeomSubDomain.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/GeomSubDomain.cpp	(revision 15396)
@@ -0,0 +1,20 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "GeomSubDomain.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	/*FUNCTION GeomSubDomain::Set {{{*/
+	void GeomSubDomain::Set(const GeomSubDomain & rec,const Geometry & Gh ,const Geometry & GhNew){
+		*this = rec;
+		edge = Gh.GetId(edge) + GhNew.edges;
+	}/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/GeomSubDomain.h
===================================================================
--- /issm/trunk/src/c/bamg/GeomSubDomain.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/GeomSubDomain.h	(revision 15396)
@@ -0,0 +1,22 @@
+#ifndef _GEOMETRICALSUBDOMAIN_H_
+#define _GEOMETRICALSUBDOMAIN_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class GeomEdge;
+	class Geometry;
+
+	class GeomSubDomain {
+		public:
+			GeomEdge *edge;
+			int              direction;   // -1 or 1
+			long             ReferenceNumber;
+
+			//Methods
+			void Set(const GeomSubDomain &,const Geometry & ,const Geometry &);
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/GeomVertex.cpp
===================================================================
--- /issm/trunk/src/c/bamg/GeomVertex.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/GeomVertex.cpp	(revision 15396)
@@ -0,0 +1,37 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "GeomVertex.h"
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	//See header file
+
+	/*Methods*/
+	/*FUNCTION GeomVertex::Corner {{{*/
+	int  GeomVertex::Corner() const {
+		return type & 4;
+	}
+	/*}}}*/
+	/*FUNCTION GeomVertex::Required {{{*/
+	int  GeomVertex::Required()const {
+		// a corner is required
+		return type & 6;
+	}
+	/*}}}*/
+	/*FUNCTION GeomVertex::SetCorner {{{*/
+	void GeomVertex::SetCorner(){
+		type |= 4;
+	}
+	/*}}}*/
+	/*FUNCTION GeomVertex::SetRequired {{{*/
+	void GeomVertex::SetRequired(){
+		type |= 2;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/GeomVertex.h
===================================================================
--- /issm/trunk/src/c/bamg/GeomVertex.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/GeomVertex.h	(revision 15396)
@@ -0,0 +1,30 @@
+#ifndef _GEOMETRICALVERTEX_H_
+#define _GEOMETRICALVERTEX_H_
+
+#include "./include.h"
+#include "BamgVertex.h"
+
+namespace bamg {
+
+	class Geometry;
+
+	class GeomVertex : public BamgVertex { 
+
+		public:
+			friend class Geometry;
+
+			int type;
+
+			//Constructors
+			GeomVertex():type(0){};
+
+			//Methods
+			int  Corner() const;
+			int  Required()const;
+			void SetCorner();
+			void SetRequired();
+
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/Geometry.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Geometry.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/Geometry.cpp	(revision 15396)
@@ -0,0 +1,969 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	static const  Direction NoDirOfSearch=Direction();
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Geometry::Geometry(){{{*/
+	Geometry::Geometry(){
+		Init();
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts){{{*/
+	Geometry::Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts){
+		Init();
+		ReadGeometry(bamggeom,bamgopts);
+		PostRead();
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::Geometry(const Geometry & Gh) (COPY operator){{{*/
+	Geometry::Geometry(const Geometry & Gh) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/Geometry)*/
+
+		long i;
+		*this = Gh;
+		NbRef =0;
+		quadtree=0;
+		vertices = nbv ? new GeomVertex[nbv] : NULL;
+		edges = nbe ? new GeomEdge[nbe]:NULL;
+		curves= nbcurves ? new Curve[nbcurves]:NULL;
+		subdomains = nbsubdomains ? new GeomSubDomain[nbsubdomains]:NULL;
+		for (i=0;i<nbe;i++)
+		 edges[i].Set(Gh.edges[i],Gh,*this);
+		for (i=0;i<nbcurves;i++)
+		 curves[i].Set(Gh.curves[i],Gh,*this);
+		for (i=0;i<nbsubdomains;i++)
+		 subdomains[i].Set(Gh.subdomains[i],Gh,*this);
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::~Geometry(){{{*/
+	Geometry::~Geometry() {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/~Geometry)*/
+		if(NbRef>0){   _printf_("Trying to delete geometry and NbRef>0, probably due to an error"); return;}
+		if(vertices)   delete [] vertices;  vertices=0;
+		if(edges)      delete [] edges;     edges=0;
+		if(quadtree)   delete    quadtree;  quadtree=0;
+		if(curves)     delete [] curves;    curves=0;nbcurves=0;
+		if(subdomains) delete [] subdomains;subdomains=0;
+		Init();
+	}
+	/*}}}*/
+
+	/*IO*/
+	/*FUNCTION Geometry::ReadGeometry{{{*/
+	void Geometry::ReadGeometry(BamgGeom* bamggeom,BamgOpts* bamgopts){
+
+		int verbose;
+		nbv=0;
+		nbe=0;
+		nbcurves=0;
+
+		double Hmin = HUGE_VAL;// the infinie value 
+		int i,j,n,i0,i1,i2,i3;
+
+		/*initialize some variables*/
+		verbose= bamgopts->verbose;
+		nbv    = bamggeom->VerticesSize[0];
+		nbe    = bamggeom->EdgesSize[0];
+
+		//some checks
+		if (bamggeom->Vertices==NULL) _error_("the domain provided does not contain any vertex");
+		if (bamggeom->Edges==NULL) _error_("the domain provided does not contain any edge");
+
+		//Vertices
+		if (bamggeom->Vertices){
+			if(verbose>5) _printf_("      processing Vertices\n");
+			if (bamggeom->VerticesSize[1]!=3) _error_("Vertices should have 3 columns");
+			vertices = new GeomVertex[nbv];
+			for (i=0;i<nbv;i++) {
+				vertices[i].r.x=(double)bamggeom->Vertices[i*3+0];
+				vertices[i].r.y=(double)bamggeom->Vertices[i*3+1];
+				vertices[i].ReferenceNumber=(long)bamggeom->Vertices[i*3+2];
+				vertices[i].DirOfSearch=NoDirOfSearch;
+				vertices[i].color =0;
+				vertices[i].type=0;
+			}
+			/*find domain extrema (pmin,pmax) that will define the square box used for by the quadtree*/
+			pmin =  vertices[0].r;
+			pmax =  vertices[0].r;
+			for (i=0;i<nbv;i++) {
+				pmin.x = Min(pmin.x,vertices[i].r.x);
+				pmin.y = Min(pmin.y,vertices[i].r.y);
+				pmax.x = Max(pmax.x,vertices[i].r.x);
+				pmax.y = Max(pmax.y,vertices[i].r.y);
+			}
+			/*Offset pmin and pmax to avoid round-off errors*/
+			R2 offset = (pmax-pmin)*0.05;
+			pmin -= offset;
+			pmax += offset;
+			/*coefIcoor is the coefficient used for integer coordinates:
+			 *                       (x-pmin.x)
+			 * Icoor x = (2^30 -1) ------------ 
+			 *                          D
+			 * where D is the longest side of the domain (direction x or y)
+			 * so that (x-pmin.x)/D is in ]0 1[
+			 *
+			 * coefIcoor = (2^30 -1)/D
+			 */
+			coefIcoor=(MaxICoor)/(Max(pmax.x-pmin.x,pmax.y-pmin.y));
+			if(coefIcoor<=0) _error_("coefIcoor should be positive");
+		}
+		else{
+			_error_("No BamgVertex provided");
+		}
+
+		//Edges
+		if (bamggeom->Edges){
+			R2      zerovector(0,0);
+			double* verticeslength=NULL;
+
+			if(verbose>5) _printf_("      processing Edges\n");
+			if (bamggeom->EdgesSize[1]!=3) _error_("Edges should have 3 columns");
+			edges = new GeomEdge[nbe];
+
+			//initialize verticeslength (sum of the lengths of the edges holding vertex)
+			verticeslength = new double[nbv];
+			for(i=0;i<nbv;i++) verticeslength[i]=0;
+
+			/*Loop over the edges*/
+			for (i=0;i<nbe;i++){
+
+				i1=(int)bamggeom->Edges[i*3+0]-1; //-1 for C indexing
+				i2=(int)bamggeom->Edges[i*3+1]-1; //-1 for C indexing
+				edges[i].v[0]= vertices + i1;     //pointer toward vertex i1 (=&vertices[i1])
+				edges[i].v[1]= vertices + i2;     //pointer toward vertex i2
+				edges[i].ReferenceNumber=(long)bamggeom->Edges[i*3+2];
+
+				//get length of edge
+				R2     x12=vertices[i2].r-vertices[i1].r;
+				double l12=sqrt((x12,x12));
+				Hmin=Min(Hmin,l12);
+
+				//initialize other fields
+				edges[i].tg[0]=zerovector;
+				edges[i].tg[1]=zerovector;
+				edges[i].AdjVertexIndex[0] = edges[i].AdjVertexIndex[1] = -1;
+				edges[i].Adj[0] = edges[i].Adj[1] = NULL;
+				edges[i].type = 0;
+
+				//Cracked?
+				if (edges[i].ReferenceNumber!=1) edges[i].SetCracked();
+
+				//prepare metric
+				vertices[i1].color++;
+				vertices[i2].color++;
+				verticeslength[i1] += l12;
+				verticeslength[i2] += l12;
+			}
+
+			// definition the default of the given mesh size 
+			for (i=0;i<nbv;i++) {
+				if (vertices[i].color > 0) 
+				 vertices[i].m=Metric(verticeslength[i] /(double) vertices[i].color);
+				else 
+				 vertices[i].m=Metric(Hmin);
+			}
+			delete [] verticeslength;
+
+		}
+		else{
+			_error_("No edges provided");
+		}
+
+		//hVertices
+		if(bamgopts->hVertices && bamgopts->hVerticesSize[0]==nbv){
+			if(verbose>5) _printf_("      processing hVertices\n");
+			for (i=0;i< nbv;i++){
+				if (!xIsNan<IssmPDouble>(bamgopts->hVertices[i])){
+					vertices[i].m=Metric((double)bamgopts->hVertices[i]);
+				}
+			}
+		}
+
+		//MetricVertices
+		if(bamgopts->metric && bamgopts->metric[0]==nbv){
+			if(verbose>5) _printf_("      processing MetricVertices\n");
+			for (i=0;i< nbv;i++) {
+				vertices[i].m = Metric((double)bamgopts->metric[i*3+0],(double)bamgopts->metric[i*3+1],(double)bamgopts->metric[i*3+2]);
+			}
+		}
+
+		//MaxCornerAngle
+		if (bamgopts->MaxCornerAngle){
+			if(verbose>5) _printf_("      processing MaxCornerAngle\n");
+			MaxCornerAngle=bamgopts->MaxCornerAngle*Pi/180;
+		}
+
+		//TangentAtEdges
+		if (bamggeom->TangentAtEdges){
+			if(verbose>5) _printf_("      processing TangentAtEdges");
+			if (bamggeom->TangentAtEdgesSize[1]!=4) _error_("TangentAtEdges should have 4 columns");
+			int n,i,j,k;
+			R2 tg;
+
+			n=bamggeom->TangentAtEdgesSize[0];
+			for (k=0;k<n;k++) {
+				i=(int)bamggeom->TangentAtEdges[k*4+0]-1; //for C indexing
+				j=(int)bamggeom->TangentAtEdges[k*4+1]-1; //for C indexing
+				tg.x=bamggeom->TangentAtEdges[k*4+2];
+				tg.y=bamggeom->TangentAtEdges[k*4+3];
+				if (i<0 || i>=nbe) _error_("TangentAtEdges first index exceeds matrix dimension");
+				if (j!=0 && j!=1)  _error_("TangentAtEdges second index should be 1 or 2 only");
+				edges[i].tg[j] = tg;
+			}
+		}
+
+		//Corners
+		if(bamggeom->Corners){
+			if(verbose>5) _printf_("      processing Corners");
+			if (bamggeom->CornersSize[1]!=1) _error_("Corners should have 1 column");
+			n=bamggeom->CornersSize[0];
+			for (i=0;i<n;i++) {     
+				j=(int)bamggeom->Corners[i]-1; //for C indexing
+				if (j>nbv-1 || j<0) _error_("Bad corner definition: should in [0 " << nbv << "]");
+				/*Required => at the same time SetRequired and SetCorner*/
+				vertices[j].SetCorner();
+				vertices[j].SetRequired();
+			}
+		}
+
+		//RequiredVertices
+		if(bamggeom->RequiredVertices){
+			if(verbose>5) _printf_("      processing RequiredVertices\n");
+			if (bamggeom->RequiredVerticesSize[1]!=1) _error_("RequiredVertices should have 1 column");
+			n=bamggeom->RequiredVerticesSize[0];
+			for (i=0;i<n;i++) {     
+				j=(int)bamggeom->RequiredVertices[i]-1; //for C indexing
+				if (j>nbv-1 || j<0) _error_("Bad RequiredVerticess  definition: should in [0 " << nbv << "]");
+				vertices[j].SetRequired();
+			}
+		}
+
+		//RequiredEdges
+		if(bamggeom->RequiredEdges){
+			if(verbose>5) _printf_("      processing RequiredEdges\n");
+			if (bamggeom->RequiredEdgesSize[1]!=1) _error_("RequiredEdges should have 1 column");
+			n=bamggeom->RequiredEdgesSize[0];
+			for (i=0;i<n;i++) {     
+				j=(int)bamggeom->RequiredEdges[i]-1; //for C indexing
+				if (j>nbe-1 || j<0) _error_("Bad RequiredEdges definition: should in [0 " << nbe << "]");
+				edges[j].SetRequired();  
+			}
+		}
+
+		//SubDomain
+		if(bamggeom->SubDomains){
+			if(verbose>5) _printf_("      processing SubDomains\n");
+			if (bamggeom->SubDomainsSize[1]!=4) _error_("SubDomains should have 4 columns");
+			nbsubdomains=bamggeom->SubDomainsSize[0];
+			subdomains = new GeomSubDomain[nbsubdomains];
+			for (i=0;i<nbsubdomains;i++){
+				i0=(int)bamggeom->SubDomains[i*4+0];
+				i1=(int)bamggeom->SubDomains[i*4+1];
+				i2=(int)bamggeom->SubDomains[i*4+2];
+				i3=(int)bamggeom->SubDomains[i*4+3];
+				if (i0!=2) _error_("Bad Subdomain definition: first number should be 2 (for Edges)");
+				if (i1>nbe || i1<=0) _error_("Bad Subdomain definition: second number should in [1 " << nbe << "] (edge number)");
+				subdomains[i].edge=edges + (i1-1);
+				subdomains[i].direction = (int) i2;
+				subdomains[i].ReferenceNumber = i3;
+			}
+		}
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::WriteGeometry{{{*/
+	void Geometry::WriteGeometry(BamgGeom* bamggeom, BamgOpts* bamgopts){
+
+		int verbose;
+		int nbreq=0;
+		int nbreqv=0;
+		int nbtan=0;
+		int nbcracked=0;
+		int i,count;
+
+		/*Get options*/
+		verbose=bamgopts->verbose;
+
+		/*Vertices*/
+		if(verbose>5) _printf_("      writing Vertices\n");
+		bamggeom->VerticesSize[0]=nbv;
+		bamggeom->VerticesSize[1]=3;
+		if (nbv){
+			bamggeom->Vertices=xNew<double>(3*nbv);
+			for (i=0;i<nbv;i++){
+				bamggeom->Vertices[i*3+0]=vertices[i].r.x;
+				bamggeom->Vertices[i*3+1]=vertices[i].r.y;
+				bamggeom->Vertices[i*3+2]=vertices[i].GetReferenceNumber();
+
+				//update counters
+				if (vertices[i].Required()) nbreqv++;
+			}
+		}
+
+		/*Edges*/
+		if(verbose>5) _printf_("      writing Edges\n");
+		bamggeom->EdgesSize[0]=nbe;
+		bamggeom->EdgesSize[1]=3;
+		if (nbe){
+			bamggeom->Edges=xNew<double>(3*nbe);
+			for (i=0;i<nbe;i++){
+				bamggeom->Edges[i*3+0]=GetId(edges[i][0])+1; //back to Matlab indexing
+				bamggeom->Edges[i*3+1]=GetId(edges[i][1])+1; //back to Matlab indexing
+				bamggeom->Edges[i*3+2]=(double)edges[i].ReferenceNumber;
+
+				//update counters
+				if (edges[i].Required()) nbreq++;
+				if (edges[i].TgA() && edges[i][0].Corner()) nbtan++;
+				if (edges[i].TgB() && edges[i][1].Corner()) nbtan++;
+			}
+		}
+
+		/*RequiredEdges*/
+		if(verbose>5) _printf_("      writing " << nbreq << " RequiredEdges\n");
+		bamggeom->RequiredEdgesSize[0]=nbreq;
+		bamggeom->RequiredEdgesSize[1]=1;
+		if (nbreq){
+			bamggeom->RequiredEdges=xNew<double>(1*nbreq);
+			count=0;
+			for (i=0;i<nbe;i++){
+				if (edges[i].Required()){
+					bamggeom->RequiredEdges[count]=i+1; //back to Matlab indexing
+					count=count+1;
+				}
+			}
+		}
+
+		//No corners
+
+		/*RequiredVertices*/
+		if(verbose>5) _printf_("      writing " << nbreqv << " RequiredVertices\n");
+		bamggeom->RequiredVerticesSize[0]=nbreqv;
+		bamggeom->RequiredVerticesSize[1]=1;
+		if (nbreqv){
+			bamggeom->RequiredVertices=xNew<double>(1*nbreqv);
+			count=0;
+			for (i=0;i<nbv;i++){
+				if (vertices[i].Required()){
+					bamggeom->RequiredVertices[count]=i+1; //back to Matlab indexing
+					count=count+1;
+				}
+			}
+		}
+
+		/*SubDomains*/
+		if(verbose>5) _printf_("      writing SubDomains\n");
+		bamggeom->SubDomainsSize[0]=nbsubdomains;
+		bamggeom->SubDomainsSize[1]=4;
+		if (nbsubdomains){
+			bamggeom->SubDomains=xNew<double>(4*nbsubdomains);
+			for (i=0;i<nbsubdomains;i++){
+				bamggeom->SubDomains[4*i+0]=2;
+				bamggeom->SubDomains[4*i+1]=GetId(subdomains[i].edge)+1; //back to Matlab indexing
+				bamggeom->SubDomains[4*i+2]=subdomains[i].direction;
+				bamggeom->SubDomains[4*i+3]=subdomains[i].ReferenceNumber;
+			}
+		}
+
+		/*TangentAtEdges*/
+		if(verbose>5) _printf_("      writing TangentAtEdges\n");
+		bamggeom->TangentAtEdgesSize[0]=nbtan;
+		bamggeom->TangentAtEdgesSize[1]=4;
+		if (nbtan){
+			bamggeom->TangentAtEdges=xNew<double>(4*nbtan);
+			count=0;
+			for (i=0;i<nbe;i++){
+				if (edges[i].TgA() && edges[i][0].Corner()){
+					bamggeom->TangentAtEdges[4*i+0]=i+1; //back to Matlab indexing
+					bamggeom->TangentAtEdges[4*i+1]=1;
+					bamggeom->TangentAtEdges[4*i+2]=edges[i].tg[0].x;
+					bamggeom->TangentAtEdges[4*i+3]=edges[i].tg[0].y;
+				}
+				if (edges[i].TgB() && edges[i][1].Corner()){
+					bamggeom->TangentAtEdges[4*i+0]=i+1; //back to Matlab indexing
+					bamggeom->TangentAtEdges[4*i+1]=2;
+					bamggeom->TangentAtEdges[4*i+2]=edges[i].tg[1].x;
+					bamggeom->TangentAtEdges[4*i+3]=edges[i].tg[1].y;
+				}
+				count=count+1;
+			}
+		}
+	}
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Geometry::Echo {{{*/
+	void Geometry::Echo(void){
+
+		_printf_("Geometry:\n");
+		_printf_("   nbv  (number of vertices) : " << nbv << "\n");
+		_printf_("   nbe  (number of edges)    : " << nbe << "\n");
+		_printf_("   nbsubdomains: " << nbsubdomains << "\n");
+		_printf_("   nbcurves: " << nbcurves << "\n");
+		_printf_("   vertices: " << vertices << "\n");
+		_printf_("   edges: " << edges << "\n");
+		_printf_("   quadtree: " << quadtree << "\n");
+		_printf_("   subdomains: " << subdomains << "\n");
+		_printf_("   curves: " << curves << "\n");
+		_printf_("   pmin (x,y): (" << pmin.x << " " << pmin.y << ")\n");
+		_printf_("   pmax (x,y): (" << pmax.x << " " << pmax.y << ")\n");
+		_printf_("   coefIcoor: " << coefIcoor << "\n");
+		_printf_("   MaxCornerAngle: " << MaxCornerAngle << "\n");
+
+		return;
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::Init{{{*/
+	void Geometry::Init(void){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/EmptyGeometry)*/
+
+		NbRef=0;
+		nbv=0;
+		nbe=0;
+		quadtree=NULL;
+		curves=NULL;
+		edges=NULL;
+		vertices=NULL;
+		nbsubdomains=0;
+		nbcurves=0;
+		subdomains=NULL;
+		MaxCornerAngle = 10*Pi/180; //default is 10 degres
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::MinimalHmin{{{*/
+	double Geometry::MinimalHmin() {
+		/* coeffIcoor = (2^30-1)/D
+		 * We cannot go beyond hmin = D/2^30 because of the quadtree
+		 * hmin is therefore approximately 2/coeffIcoor */
+		return 2.0/coefIcoor;
+	}/*}}}*/
+	/*FUNCTION Geometry::MaximalHmax{{{*/
+	double Geometry::MaximalHmax() {
+		return Max(pmax.x-pmin.x,pmax.y-pmin.y);
+	}/*}}}*/
+	/*FUNCTION Geometry::GetId(const GeomVertex &t){{{*/
+	long Geometry::GetId(const GeomVertex & t) const  {
+		return &t - vertices;
+	}/*}}}*/
+	/*FUNCTION Geometry::GetId(const GeomVertex * t){{{*/
+	long Geometry::GetId(const GeomVertex * t) const  {
+		return t - vertices;
+	}/*}}}*/
+	/*FUNCTION Geometry::GetId(const GeomEdge & t){{{*/
+	long Geometry::GetId(const GeomEdge & t) const  {
+		return &t - edges;
+	}/*}}}*/
+	/*FUNCTION Geometry::GetId(const GeomEdge * t){{{*/
+	long Geometry::GetId(const GeomEdge * t) const  {
+		return t - edges;
+	}/*}}}*/
+	/*FUNCTION Geometry::GetId(const Curve * c){{{*/
+	long Geometry::GetId(const Curve * c) const  {
+		return c - curves;
+	}/*}}}*/
+	/*FUNCTION Geometry::Containing{{{*/
+	GeomEdge* Geometry::Containing(const R2 P,  GeomEdge * start) const {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/Contening)*/
+
+		GeomEdge* on =start,* pon=0;
+		// walk with the cos on geometry
+		int counter=0;
+		while(pon != on){  
+			counter++;
+			_assert_(counter<100);
+			pon = on;
+			R2 A= (*on)[0];
+			R2 B= (*on)[1];
+			R2 AB = B-A;
+			R2 AP = P-A;
+			R2 BP = P-B;
+			if ( (AB,AP) < 0) 
+			 on = on->Adj[0];
+			else if ( (AB,BP)  > 0) 
+			 on = on->Adj[1];
+			else
+			 return on;
+		}
+		return on;
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::PostRead{{{*/
+	void Geometry::PostRead(){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/AfterRead)*/
+
+		long          i          ,j,k;
+		long         *head_v   = new long[nbv];
+		long         *next_p   = new long[2 *nbe];
+		float        *eangle   = new float[nbe];
+		double        eps      = 1e-20;
+		BamgQuadtree  quadtree;                            // build quadtree to find duplicates
+		BamgVertex   *v0       = vertices;
+
+		k=0;
+
+		//build quadtree for this geometry
+		for (i=0;i<nbv;i++){
+
+			/*build integer coordinates (non unique)
+			  these coordinates are used by the quadtree to group
+			  the vertices by groups of 5:
+			  All the coordinates are transformed to ]0,1[^2
+			  then, the integer coordinates are computed using 
+			  the transformation ]0,1[^2 -> [0 2^30-1[^2 for a quadtree of depth 30*/
+			vertices[i].i=R2ToI2(vertices[i].r); 
+
+			/*find nearest vertex already present in the quadtree (NULL if empty)*/
+			BamgVertex* v=quadtree.NearestVertex(vertices[i].i.x,vertices[i].i.y); 
+
+			/*if there is a vertex found that is to close to vertices[i] -> error*/
+			if( v && Norme1(v->r - vertices[i].r) < eps ){
+				_printf_("reference numbers: " << v->ReferenceNumber << " " << vertices[i].ReferenceNumber << "\n");
+				_printf_("Id: " << i+1 << "\n");
+				_printf_("Coords: ["<<v->r.x<<" "<<v->r.y<<"] ["<<vertices[i].r.x<<" "<<vertices[i].r.y<<"]\n");
+
+				delete [] next_p;
+				delete [] head_v;
+				delete [] eangle;
+				_error_("two points of the geometry are very closed to each other (see reference numbers above)");
+			}
+
+			/*Add vertices[i] to the quadtree*/
+			quadtree.Add(vertices[i]);
+		}
+
+		/* Here we use a powerful chaining algorithm
+		 *
+		 * 1. What is a chaining algorithm?
+		 *
+		 * If F is a function that goes from i in [0 n] to j in [0 m]
+		 * and we want to compute the reciprocal function F-1 of F
+		 * (what are the antecedents of a given j in Im(F) )
+		 * We use 2 lists:
+		 *    head_F[j] that holds the head of lists
+		 *    next_F[i] that holds the list of elements that have the same image
+		 *
+		 * Example:
+		 *    i1, i2, ..., ip in [0,n] are all antecedents of a given j in [0 m]
+		 *    head_F[j] = ip
+		 *    next_F[ip]= ip-1
+		 *    ....
+		 *    next_F[i2]= i1
+		 *    next_F[i1]= -1  //end of the list
+		 *
+		 * Algorithm:
+		 *    for(j=0;j<m;j++)  head_F[j] = -1 //initialization
+		 *    for(i=0;i<n;i++){
+		 *       j=F[i];
+		 *       next_F[i]= head_F[j];
+		 *       head_F[j]=i;
+		 *    }
+		 * 
+		 *    Then, we can go through all the elements that have for image j:
+		 *    for(i=head_F[j]; i!=-1; i=next_F[i])
+		 *    initialization of i by i=head_F[j]
+		 *    stop the loop when i=-1 (end of the chain)
+		 *    iterate using i=next_F[i] (next element that have for image j)
+		 * 
+		 * 2. How to use this algorithm here?
+		 * 
+		 * Here F is a function that associates two vertices v0 and v1 for a given edge E
+		 * We want to build the reciprocal function: what are the edges that contains
+		 * a vertex v?
+		 * To do so, we use the same chaining algorithm but there is a difficulty
+		 * coming from the fact that for F we have a couple of vertices and not one 
+		 * vertex.
+		 * To overcome this difficulty, we use a global indexing exactly like in 
+		 * C/C++ so that
+		 * a member of a 2-column-table can be described by one index p=i*2+j
+		 * i=(int)p/2 line number of p
+		 * j=p%2      column number of p
+		 *
+		 * Algorithm:
+		 *    for(i=0;i<nbv;i++)  head_v[i] = -1 //initialization
+		 *    for(i=0;i<nbe;i++){
+		 *       for(j=0;j<2;j++){
+		 *          p=2*i+j;
+		 *          v=edges(i,j);
+		 *          next_p[p]= head_v[v];
+		 *          head_v[v]=p;
+		 *       }
+		 *    }
+		 */
+
+		//initialize head_v as -1
+		for (i=0;i<nbv;i++) head_v[i]=-1;
+		k=0;
+		for (i=0;i<nbe;i++) {
+			//compute vector of edge i that goes from vertex 0 to vertex 1
+			R2 v10=edges[i].v[1]->r - edges[i].v[0]->r;
+			double lv10=Norme2(v10);
+			//check that its length is not 0
+			if(lv10==0){
+				delete [] next_p;
+				delete [] head_v;
+				delete [] eangle;
+				_error_("Length of edge " << i << " is 0");
+			}
+			//compute angle in [-Pi Pi]
+			eangle[i] = atan2(v10.y,v10.x);
+			//build chains head_v and next_p
+			for (j=0;j<2;j++){
+				long v=GetId(edges[i].v[j]);
+				next_p[k]=head_v[v];
+				head_v[v]=k++; //post increment: head_v[v]=k; and then k=k+1;
+			}
+		}
+
+		//sort head_v by order of increasing edges angle
+		for (i=0;i<nbv;i++) {
+			int exch=1,ord=0;      
+
+			//exchange vertices position in head_v and next_p till tey are sorted
+			while (exch){
+				long *p=head_v+i;               
+				long *po=p;                     
+				long  n=*p;                     
+				register float angleold=-1000 ; // angle = - infinity
+				ord=0; exch=0;
+
+				// loop over the edges that contain the vertex i (till -1)
+				while (n >=0){
+					ord++;
+					long  i1=n/2;       // i1 = floor (n/2)      -> Edge number
+					long  j1=n%2;       // j1 = 1 if n is odd    -> Vertex index for this edge (0 or 1)
+					long* pn=next_p+n;
+
+					//Next vertex index
+					n=*pn;                       
+
+					//compute angle between horizontal axis and v0->v1
+					float angle = j1 ? OppositeAngle(eangle[i1]):  eangle[i1]; 
+
+					//exchange if the current edge angle is smaller than the previous one
+					if (angleold > angle){
+						exch=1;
+						*pn=*po;  // next_p[n] = n + 1
+						*po=*p;   // 
+						*p=n;     // next_p[n+1] = n
+						po=pn;    // po now point toward pn (invert next and current)
+					}
+
+					//else, continue going to the next edge position
+					else{                        //  to have : po -> p -> pn
+						angleold=angle; // update maximum angle
+						po=p;           // po now point toward p  (current position)
+						p=pn;           // p  now point toward pn (next position)
+					}
+				}
+			}
+
+			// angular test on current vertex to guess whether it is a corner (ord = number of edges holding i)
+			if(ord==2) { 
+				long  n1 = head_v[i];
+				long  n2 = next_p[n1];
+				long  i1 = n1/2, i2 = n2/2; // edge number
+				long  j1 = n1%2, j2 = n2%2; // vertex in the edge 
+				float angle1=  j1 ? OppositeAngle(eangle[i1]) : eangle[i1];
+				float angle2= !j2 ? OppositeAngle(eangle[i2]) : eangle[i2];
+				float da12 = Abs(angle2-angle1);
+				if (( da12 >= MaxCornerAngle ) && (da12 <= 2*Pi -MaxCornerAngle)) {
+					vertices[i].SetCorner() ; 
+				}
+				// if the edge type/referencenumber a changing then is SetRequired();
+				if (edges[i1].type != edges[i2].type || edges[i1].Required()){
+					vertices[i].SetRequired();
+				}
+				if (edges[i1].ReferenceNumber != edges[i2].ReferenceNumber) {
+					vertices[i].SetRequired();
+				}
+			}
+			if(ord != 2) {
+				vertices[i].SetCorner();
+			}
+
+			/*close the list around the vertex to have a circular loop*/
+			long no=-1, ne = head_v[i];
+			while (ne >=0) ne = next_p[no=ne];        
+			if(no>=0) next_p[no] = head_v[i];
+		}
+
+		/*Check that the list makes sense (we have all the time the same vertex)
+		 * and build adjacent edges*/
+		k =0;
+		for (i=0;i<nbe;i++){
+			for (j=0;j<2;j++){
+
+				long n1 = next_p[k++]; 
+				long i1 = n1/2 ,j1=n1%2;
+
+				if( edges[i1].v[j1] != edges[i].v[j]) _error_("Problem while processing edges: check the edge list");
+
+				edges[i1].Adj[j1] = edges + i;
+				edges[i1].AdjVertexIndex[j1] = j;
+			}
+		}
+
+		/* generation of  all the tangents*/
+		for (i=0;i<nbe;i++) {
+			R2    AB =edges[i].v[1]->r -edges[i].v[0]->r;// AB = vertex0 -> vertex1
+			double lAB=Norme2(AB);                       // Get length of AB
+			double ltg2[2]={0.0};                        // initialize tangent
+
+			//loop over the 2 vertices of the edge
+			for (j=0;j<2;j++) {
+				R2     tg =edges[i].tg[j];
+				double ltg=Norme2(tg);
+
+				//by default, tangent=[0 0]
+				if(ltg==0){
+					//if the current vertex of the edge is not a corner
+					if(!edges[i].v[j]->Corner()){
+						/*The tangent is set as the vector between the
+						 * previous and next vertices connected to current vertex
+						 * normed by the edge length*/
+						tg = edges[i].v[1-j]->r - edges[i].Adj[j]->v[1-edges[i].AdjVertexIndex[j]]->r;
+						ltg= Norme2(tg);
+						tg = tg *(lAB/ltg);
+						ltg= lAB;
+					}
+					//else:  a Corner no tangent => nothing to do    
+				}
+				else{
+					//tangent has already been computed
+					tg = tg*(lAB/ltg),ltg=lAB;
+				}
+
+				ltg2[j] = ltg;
+
+				if ((tg,AB)<0) tg = -tg;
+
+				edges[i].tg[j]=tg;
+			}
+			if (ltg2[0]!=0) edges[i].SetTgA();
+			if (ltg2[1]!=0) edges[i].SetTgB();
+		} 
+
+		/* generation of  all curves (from corner to corner)*/
+		/*We proceed in 2 steps: first allocate, second build*/
+		for (int step=0;step<2;step++){
+
+			//unmark all edges
+			for (i=0;i<nbe;i++) edges[i].SetUnMark();
+			long  nb_marked_edges=0;
+
+			//initialize number of curves
+			nbcurves = 0;
+
+			for (int level=0;level<2 && nb_marked_edges!=nbe;level++){
+				for (i=0;i<nbe;i++){
+
+					GeomEdge & ei=edges[i];   
+					for(j=0;j<2;j++){
+						/*If current edge ei is unmarked and (level=1 or vertex i is required (corner)):
+						 * we do have the first edge of a new curve*/
+						if (!ei.Mark() && (level || ei[j].Required())) { 
+							int k0=j,k1;
+							GeomEdge   *e=&ei;
+							GeomVertex *a=(*e)(k0); // begin 
+							if(curves){
+								curves[nbcurves].FirstEdge=e;
+								curves[nbcurves].FirstVertexIndex=k0;
+							}
+							int nee=0;
+							for(;;){ 
+								nee++;
+								k1 = 1-k0; // next vertex of the edge 
+								e->SetMark();
+								nb_marked_edges++;
+								e->CurveNumber=nbcurves;
+								GeomVertex *b=(*e)(k1);
+
+								//break if we have reached the other end of the curve
+								if (a==b || b->Required()){
+									if(curves){
+										curves[nbcurves].LastEdge=e;
+										curves[nbcurves].LastVertexIndex=k1;
+									}
+									break;
+								}
+								//else: go to next edge (adjacent)
+								else{
+									k0 = e->AdjVertexIndex[k1];//  vertex in next edge
+									e  = e->Adj[k1]; // next edge
+								}
+							}
+							nbcurves++;
+							if(level) a->SetRequired();
+						}
+					}
+				} 
+			}
+			_assert_(nb_marked_edges && nbe);
+			//allocate if first step
+			if(step==0) curves=new Curve[nbcurves];
+		} 
+
+		/*clean up*/
+		delete [] next_p;
+		delete [] head_v;
+		delete [] eangle;
+
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::ProjectOnCurve {{{*/
+	GeomEdge* Geometry::ProjectOnCurve(const Edge &e,double s,BamgVertex &V,VertexOnGeom &GV) const {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/ProjectOnCurve)*/
+		/*Add a vertex on an existing geometrical edge according to the metrics of the two vertices constituting the edge*/
+
+		double save_s=s;
+		int NbTry=0;
+
+retry:
+
+		s=save_s;
+		GeomEdge* on=e.GeomEdgeHook;
+		if (!on){
+			_error_("ProjectOnCurve error message: edge provided should be on geometry");
+		}
+		if (!e[0].GeomEdgeHook ||  !e[1].GeomEdgeHook){
+			_error_("ProjectOnCurve error message: at least one of the vertex of the edge provided is not on geometry");
+		}
+
+		//Get the two vertices of the edge
+		const BamgVertex &v0=e[0];
+		const BamgVertex &v1=e[1];
+
+		//Get position of V0, V1 and vector v0->v1
+		R2 V0=v0,V1=v1,V01=V1-V0;
+
+		//Get geometrical vertices corresponding to v0 and v1
+		VertexOnGeom  vg0=*v0.GeomEdgeHook,  vg1=*v1.GeomEdgeHook;
+
+		//build two pointers towrad current geometrical edge
+		GeomEdge *eg0=on, *eg1=on;
+
+		//Get edge direction and swap v0 and v1 if necessary
+		R2 Ag=(R2)(*on)[0],Bg=(R2)(*on)[1],AB=Bg-Ag; 
+		int OppositeSens = (V01,AB)<0;
+		int direction0=0,direction1=1;
+		if (OppositeSens) s=1-s,Exchange(vg0,vg1),Exchange(V0,V1);
+
+		//Compute metric of new vertex as a linear interpolation of the two others
+		V.m=Metric(1.0-s,v0,s,v1);
+
+		const int mxe=100;
+		GeomEdge* ge[mxe+1];
+		int     directionge[mxe+1];
+		double  lge[mxe+1];
+		int bge=mxe/2,tge=bge;
+		ge[bge] = e.GeomEdgeHook;
+		directionge[bge]=1;
+
+		while(eg0!=(GeomEdge*)vg0 && (*eg0)(direction0)!=(GeomVertex*)vg0){ 
+			if (bge<=0) {
+				if(NbTry) {
+					_printf_("Fatal Error: on the class Mesh before call Geometry::ProjectOnCurve\n");
+					_printf_("That bug might come from:\n");
+					_printf_(" 1)  a mesh edge  containing more than " << mxe/2 << " geometrical edges\n");
+					_printf_(" 2)  code bug : be sure that we call   Mesh::SetVertexFieldOn() before\n");
+					_printf_("To solve the problem do a coarsening of the geometrical mesh or change the constant value of mxe (dangerous)\n");
+					_error_("see above");
+				}
+				NbTry++;
+				goto retry;
+			}
+			GeomEdge* tmpge = eg0;
+			ge[--bge] =eg0 = eg0->Adj[direction0];
+			_assert_(bge>=0 && bge<=mxe);
+			direction0 = 1-( directionge[bge] = tmpge->AdjVertexIndex[direction0]);
+		}
+		while (eg1 != (GeomEdge*) vg1  &&  (*eg1)(direction1) != (GeomVertex*) vg1) { 
+			if(tge>=mxe ) { 
+				_printf_("WARNING: on the class Mesh before call Geometry::ProjectOnCurve is having issues (isn't it Eric?)\n");
+				NbTry++;
+				if (NbTry<2) goto retry;
+				_printf_("Fatal Error: on the class Mesh before call Geometry::ProjectOnCurve\n");
+				_printf_("That bug might come from:\n");
+				_printf_(" 1)  a mesh edge  contening more than " << mxe/2 << " geometrical edges\n");
+				_printf_(" 2)  code bug : be sure that we call   Mesh::SetVertexFieldOn() before\n");
+				_printf_("To solve the problem do a coarsening of the geometrical mesh or change the constant value of mxe (dangerous)\n");
+				_error_("see above");
+			}
+			GeomEdge* tmpge = eg1;
+			ge[++tge] =eg1 = eg1->Adj[direction1];
+			directionge[tge]= direction1 = 1-tmpge->AdjVertexIndex[direction1];
+			_assert_(tge>=0 && tge<=mxe);
+		}
+
+		if ((*eg0)(direction0)==(GeomVertex*)vg0)
+		 vg0=VertexOnGeom(*(BamgVertex*) vg0,*eg0,direction0); //vg0 = absisce
+
+		if ((*eg1)(direction1)==(GeomVertex*)vg1)
+		 vg1=VertexOnGeom(*(BamgVertex*) vg1,*eg1,direction1);
+
+		double sg;
+		if (eg0 == eg1) { 
+			register double s0=vg0,s1=vg1;
+			sg =  s0*(1.0-s) +  s*s1;
+			on=eg0;
+		}
+		else {
+			R2 AA=V0,BB;
+			double s0,s1;
+			int i=bge;
+			double ll=0;
+			for(i=bge;i<tge;i++){
+				_assert_(i>=0 && i<=mxe);
+				BB =  (*ge[i])[directionge[i]];
+				lge[i]=ll += Norme2(AA-BB);
+				AA=BB ;}
+				lge[tge]=ll+=Norme2(AA-V1); 
+				// search the geometrical edge
+				_assert_(s<=1.0);
+				double ls= s*ll;
+				on =0;
+				s0 = vg0;
+				s1= directionge[bge];
+				double l0=0,l1;
+				i=bge;
+				while (  (l1=lge[i]) < ls ) {
+					_assert_(i>=0 && i<=mxe);
+					i++,s0=1-(s1=directionge[i]),l0=l1;
+				}
+				on=ge[i];
+				if (i==tge) 
+				 s1=vg1;
+
+				s  =(ls-l0)/(l1-l0);
+				sg =s0*(1.0-s)+s*s1;    
+		} 
+		_assert_(on);
+		V.r= on->F(sg);
+		GV=VertexOnGeom(V,*on,sg);
+		return on;
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::R2ToI2{{{*/
+	I2 Geometry::R2ToI2(const R2 & P) const {
+		/*coefIcoor is the coefficient used for integer coordinates:
+		 *                       (x-pmin.x)
+		 * Icoor x = (2^30 -1) ------------ 
+		 *                          D
+		 * where D is the longest side of the domain (direction x or y)
+		 * so that (x-pmin.x)/D is in ]0 1[
+		 *
+		 * coefIcoor = (2^30 -1)/D
+		 */
+		return  I2( (Icoor1) (coefIcoor*(P.x-pmin.x)) ,(Icoor1) (coefIcoor*(P.y-pmin.y)) );
+	}/*}}}*/
+	/*FUNCTION Geometry::UnMarkEdges{{{*/
+	void Geometry::UnMarkEdges() {
+		for (int i=0;i<nbe;i++) edges[i].SetUnMark();
+	}/*}}}*/
+} 
Index: /issm/trunk/src/c/bamg/Geometry.h
===================================================================
--- /issm/trunk/src/c/bamg/Geometry.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/Geometry.h	(revision 15396)
@@ -0,0 +1,68 @@
+#ifndef _GEOMETRY_H_
+#define _GEOMETRY_H_
+
+#include "./include.h"
+#include "./BamgGeom.h"
+#include "./BamgOpts.h"
+#include "./GeomVertex.h"
+#include "./GeomEdge.h"
+#include "./Curve.h"
+
+namespace bamg {
+
+	class Triangle;
+	class BamgQuadtree;
+	class GeomSubDomain;
+	class Edge;
+
+	class Geometry { 
+
+		public:
+
+			long           NbRef;                 // counter of ref on the this class if 0 we can delete
+			long           nbv;                   // number of vertices
+			long           nbe;                   // number of edges
+			long           nbsubdomains;
+			long           nbcurves;
+			GeomVertex    *vertices;
+			GeomEdge      *edges;
+			BamgQuadtree  *quadtree;
+			GeomSubDomain *subdomains;
+			Curve         *curves;
+			R2             pmin,pmax;             // domain extrema coordinates
+			double         coefIcoor;             // coef to integer Icoor1;
+			double         MaxCornerAngle;
+
+			//Constructor/Destructors
+			~Geometry(); 
+			Geometry();
+			Geometry(const Geometry & Gh);
+			Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts);
+
+			//Operators
+			const GeomVertex &operator[](long i) const { return vertices[i]; };
+			GeomVertex       &operator[](long i) { return vertices[i];       };
+			const GeomEdge   &operator()(long i) const { return edges[i];    };
+			GeomEdge         &operator()(long  i) { return edges[i];         };
+
+			//Methods
+			void             Echo();
+			I2               R2ToI2(const R2 &P) const;
+			double           MinimalHmin();
+			double           MaximalHmax();
+			void             ReadGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
+			void             Init(void);
+			void             PostRead();
+			long             GetId(const GeomVertex &t) const;
+			long             GetId(const GeomVertex *t) const;
+			long             GetId(const GeomEdge &t) const;
+			long             GetId(const GeomEdge *t) const;
+			long             GetId(const Curve *c) const;
+			void             UnMarkEdges();
+			GeomEdge *ProjectOnCurve(const Edge &,double,BamgVertex &,VertexOnGeom &) const;
+			GeomEdge *Containing(const R2 P, GeomEdge *start) const;
+			void             WriteGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp
===================================================================
--- /issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/ListofIntersectionTriangles.cpp	(revision 15396)
@@ -0,0 +1,424 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+#include "./det.h"
+
+namespace bamg {
+
+	/*Constructors Destructors*/
+	/*FUNCTION ListofIntersectionTriangles::ListofIntersectionTriangles{{{*/
+	ListofIntersectionTriangles::ListofIntersectionTriangles(int n,int m)
+	  : MaxSize(n), Size(0), len(-1),state(-1),lIntTria(new IntersectionTriangles[n]) ,
+	  NbSeg(0), MaxNbSeg(m), lSegsI(new SegInterpolation[m]){
+	  }
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::~ListofIntersectionTriangles{{{*/
+	ListofIntersectionTriangles::~ListofIntersectionTriangles(){
+		if (lIntTria) delete [] lIntTria,lIntTria=0;
+		if (lSegsI) delete [] lSegsI,lSegsI=0;
+	} 
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION ListofIntersectionTriangles::Init{{{*/
+	void ListofIntersectionTriangles::Init(void){
+		state=0;
+		len=0;
+		Size=0;
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::Length{{{*/
+	double  ListofIntersectionTriangles::Length(){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Length)*/
+
+		// computation of the length
+
+		// check Size
+		if (Size<=0){
+			_error_("Size<=0");
+		}
+
+		Metric Mx,My;
+		int ii,jj;
+		R2 x,y,xy;
+
+		SegInterpolation* SegI=lSegsI;
+		SegI=lSegsI;
+		lSegsI[NbSeg].last=Size;
+		int EndSeg=Size;
+
+		y = lIntTria[0].x;
+		double sxy, s = 0;
+		lIntTria[0].s =0;
+		SegI->lBegin=s;
+
+		for (jj=0,ii=1;ii<Size;jj=ii++) {  
+			// seg jj,ii
+			x  = y;
+			y  = lIntTria[ii].x;
+			xy = y-x;
+			Mx = lIntTria[ii].m;
+			My = lIntTria[jj].m;
+			sxy= LengthInterpole(Mx,My,xy);
+			s += sxy;
+			lIntTria[ii].s = s;
+			if (ii == EndSeg){
+				SegI->lEnd=s;
+				SegI++;
+				EndSeg=SegI->last;
+				SegI->lBegin=s;
+			}
+		}
+		len = s;
+		SegI->lEnd=s;
+
+		return s;
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::NewItem(Triangle * tt,double d0,double d1,double d2) {{{*/
+	int  ListofIntersectionTriangles::NewItem(Triangle * tt,double d0,double d1,double d2) { 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewItem)*/
+
+		register int n;
+		R2 x(0,0);
+		if ( d0) x =      (*tt)[0].r * d0;
+		if ( d1) x = x +  (*tt)[1].r * d1;
+		if ( d2) x = x +  (*tt)[2].r * d2;
+		// newer add same point 
+		if(!Size ||  Norme2_2(lIntTria[Size-1].x-x)) {
+			if (Size==MaxSize) ReShape();
+			lIntTria[Size].t=tt;
+			lIntTria[Size].bary[0]=d0;
+			lIntTria[Size].bary[1]=d1;
+			lIntTria[Size].bary[2]=d2;
+			lIntTria[Size].x = x;
+			Metric m0,m1,m2;
+			register BamgVertex * v;
+			if ((v=(*tt)(0))) m0    = v->m;
+			if ((v=(*tt)(1))) m1    = v->m;
+			if ((v=(*tt)(2))) m2    = v->m;
+			lIntTria[Size].m =  Metric(lIntTria[Size].bary,m0,m1,m2);
+			n=Size++;}
+		else n=Size-1;
+		return n;
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::NewItem(R2 A,const Metric & mm){{{*/
+	int ListofIntersectionTriangles::NewItem(R2 A,const Metric & mm) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewItem)*/
+
+		register int n;
+		if(!Size ||  Norme2_2(lIntTria[Size-1].x-A)) {
+			if (Size==MaxSize) ReShape();
+			lIntTria[Size].t=0;
+			lIntTria[Size].x=A;
+			lIntTria[Size].m=mm;
+			n=Size++;
+		}
+		else  n=Size-1;
+		return  n; 
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::NewPoints{{{*/
+	long ListofIntersectionTriangles::NewPoints(BamgVertex* vertices,long &nbv,long maxnbv){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewPoints)*/
+
+		//If length<1.5, do nothing
+		double s=Length();
+		if (s<1.5) return 0;
+
+		const long nbvold=nbv;
+		int ii = 1 ;
+		R2 y,x;
+		Metric My,Mx ;
+		double sx =0,sy;
+		int nbi=Max(2,(int) (s+0.5));
+		double sint=s/nbi;
+		double si  =sint;
+
+		int EndSeg=Size;
+		SegInterpolation* SegI=NULL;
+		if (NbSeg) SegI=lSegsI,EndSeg=SegI->last;
+
+		for (int k=1;k<nbi;k++){
+			while ((ii < Size) && ( lIntTria[ii].s <= si )){
+				if (ii++ == EndSeg){
+					SegI++;
+					EndSeg=SegI->last;
+				}
+			}
+
+			int ii1=ii-1;
+			x  =lIntTria[ii1].x;
+			sx =lIntTria[ii1].s;
+			Metric Mx=lIntTria[ii1].m;
+			y  =lIntTria[ii].x;
+			sy =lIntTria[ii].s;
+			Metric My=lIntTria[ii].m;
+			double lxy = sy-sx;
+			double cy = abscisseInterpole(Mx,My,y-x,(si-sx)/lxy);
+
+			R2 C;
+			double cx = 1-cy;
+			C = SegI ? SegI->F(si): x * cx + y *cy;
+			//C.Echo();
+			//x.Echo();
+			//y.Echo();
+			//_printf_("cx = " << cx << ", cy=" << cy << "\n");
+
+			si += sint;
+			if ( nbv<maxnbv) {
+				vertices[nbv].r = C;
+				vertices[nbv++].m = Metric(cx,lIntTria[ii-1].m,cy,lIntTria[ii].m);
+			}
+			else return nbv-nbvold;
+		  }
+		return nbv-nbvold;
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::NewSubSeg{{{*/
+	void  ListofIntersectionTriangles::NewSubSeg(GeomEdge *e,double s0,double s1){ 
+		long int verbosity=0;
+		if (NbSeg>=MaxNbSeg) {
+			int mneo= MaxNbSeg;
+			MaxNbSeg *= 2;
+			if (verbosity>3){
+				_printf_("   reshape lSegsI from " << mneo << " to " << MaxNbSeg << "\n");
+			}
+			_assert_(lSegsI && NbSeg<MaxNbSeg);
+			SegInterpolation * lEn =  new SegInterpolation[MaxNbSeg];
+			for (int i=0;i< NbSeg;i++) lEn[i] = lSegsI[MaxNbSeg]; // copy old to new            
+			delete []  lSegsI; // remove old
+			lSegsI = lEn;        
+		}
+		if (NbSeg) lSegsI[NbSeg-1].last=Size;
+		lSegsI[NbSeg].e=e;
+		lSegsI[NbSeg].sBegin=s0;
+		lSegsI[NbSeg].sEnd=s1;     
+		NbSeg++;           
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::ReShape{{{*/
+	void ListofIntersectionTriangles::ReShape(){ 
+
+		register int newsize = MaxSize*2;
+		IntersectionTriangles* nw = new IntersectionTriangles[newsize];
+		_assert_(nw);
+
+		// recopy
+		for (int i=0;i<MaxSize;i++) nw[i] = lIntTria[i];       
+		long int verbosity=0;
+		if(verbosity>3) _printf_("   ListofIntersectionTriangles  ReShape Maxsize " << MaxSize << " -> " << MaxNbSeg << "\n");
+		MaxSize = newsize; 
+		delete [] lIntTria;// remove old
+		lIntTria = nw; // copy pointer
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::SplitEdge{{{*/
+	void ListofIntersectionTriangles::SplitEdge(const Mesh & Bh, const R2 &A,const R2  &B,int nbegin) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ListofIntersectionTriangles)*/
+
+		Triangle *tbegin, *t;
+
+		long int verbose=2;
+		Icoor2 deta[3], deti,detj;
+		double ba[3];
+		int nbt =0,ifirst=-1,ilast;
+		int i0,i1,i2;
+		int ocut,i,j,k=-1;
+		//  int OnAVertices =0;
+		Icoor2 dt[3];
+		I2 a = Bh.R2ToI2(A) ,b= Bh.R2ToI2(B);// compute  the Icoor a,b
+		I2 vi,vj;  
+		int iedge =-1;// not a edge
+
+		if(nbegin)  {// optimisation 
+			// we suppose  knowing the starting  triangle
+			t=tbegin=lIntTria[ilast=(Size-1)].t;
+			if (tbegin->det>=0) 
+			 ifirst = ilast;}  
+		else {// not optimisation 
+			Init();
+			t=tbegin = Bh.TriangleFindFromCoord(a,deta);
+			if( t->det>=0)
+			 ilast=NewItem(t,double(deta[0])/t->det,double(deta[1])/t->det,double(deta[2])/t->det);
+			else 
+			  {// find the nearest boundary edge  of the vertex A
+				// find a edge or such normal projection a the edge IJ is on the edge
+				//   <=> IJ.IA >=0 && IJ.AJ >=0
+				ilast=ifirst;
+				double ba,bb;
+				AdjacentTriangle edge=CloseBoundaryEdge(a,t,ba,bb);
+				BamgVertex & v0 = *edge.EdgeVertex(0), & v1 = *edge.EdgeVertex(1);
+				NewItem(A,Metric(ba,v0,bb,v1));
+				t=edge;
+				// test if the point b is in the same side
+				if (det(v0.i,v1.i,b)>=0) {
+					AdjacentTriangle edge=CloseBoundaryEdge(a,t,ba,bb);
+					BamgVertex & v0 = *edge.EdgeVertex(0), & v1 = *edge.EdgeVertex(1);
+					NewItem(A,Metric(ba,v0,bb,v1));
+					return;
+				}
+			  } // find the nearest boundary edge  of the vertex A
+		} // end not optimisation 
+		if (t->det<0) {  // outside departure
+			while (t->det <0) { // intersection boundary edge and a,b,
+				k=(*t)(0) ?  ((  (*t)(1) ? ( (*t)(2) ? -1 : 2) : 1  )) : 0;
+				if (k<0){
+					_error_("k<0");
+				}
+				ocut = OppositeEdge[k];
+				i=VerticesOfTriangularEdge[ocut][0];
+				j=VerticesOfTriangularEdge[ocut][1];
+				vi=(*t)[i];
+				vj=(*t)[j];
+				deti = bamg::det(a,b,vi);
+				detj = bamg::det(a,b,vj);
+				if (deti>0) // go to  i direction on gamma
+				 ocut = PreviousEdge[ocut];      
+				else if (detj<=0) // go to j direction on gamma
+				 ocut = NextEdge[ocut];         
+				AdjacentTriangle tadj =t->Adj(ocut);
+				t = tadj;
+				iedge= tadj; 
+				if (t == tbegin) { // 
+					double ba,bb;
+					long int verbose=2;
+					AdjacentTriangle edge=CloseBoundaryEdge(a,t,ba,bb);
+					BamgVertex & v0 = *edge.EdgeVertex(0), & v1 = *edge.EdgeVertex(1);
+					NewItem(A,Metric(ba,v0,bb,v1));
+					return;
+				}
+			} //  end while (t->det <0)
+			// theoriticaly we have: deti =<0 and detj>0
+
+			// computation of barycentric coor
+			// test if the point b is on size on t
+			// we revert vi,vj because vi,vj is def in Adj triangle
+			if ( det(vi,vj,b)>=0) {
+				t=tbegin;
+				double ba,bb;
+				AdjacentTriangle edge=CloseBoundaryEdge(b,t,ba,bb);
+				NewItem(B,Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1)));
+				return;
+			}
+			else
+			  {
+				k = OppositeVertex[iedge];
+				i=VerticesOfTriangularEdge[iedge][0];
+				j=VerticesOfTriangularEdge[iedge][1];
+				double dij = detj-deti;
+				if (i+j+k != 0 + 1 +2){
+					_error_("i+j+k != 0 + 1 +2");
+				}
+				ba[j] =  detj/dij;
+				ba[i] = -deti/dij;
+				ba[k] = 0;
+				ilast=NewItem(t,ba[0],ba[1],ba[2]); }
+		}  //  outside departure
+
+		// recherche the intersection of [a,b] with Bh Mesh.
+		// we know  a triangle ta contening the vertex a
+		// we have 2 case for intersection [a,b] with a edge [A,B] of Bh
+		// 1) the intersection point is in ]A,B[
+		// 2)                        is A or B
+		// first version --- 
+		for (;;) {
+			//    t->Draw();
+			if (iedge < 0) {
+				i0 =0;i1=1;i2=2;
+				dt[0] =bamg::det(a,b,(*t)[0]);
+				dt[1] =bamg::det(a,b,(*t)[1]);
+				dt[2] =bamg::det(a,b,(*t)[2]);}
+			else {
+				i2 = iedge;
+				i0 = NextEdge[i2];
+				i1 = NextEdge[i0]; 
+				dt[VerticesOfTriangularEdge[iedge][0]] = detj;// we revert i,j because
+				dt[VerticesOfTriangularEdge[iedge][1]] = deti;// we take the Triangle by the other side
+				dt[iedge] = det(a,b,(*t)[OppositeVertex[iedge]]);}
+
+				// so we have just to see the transition from - to + of the det0..2 on edge of t
+				// because we are going from a to b
+				if       ((dt[i=VerticesOfTriangularEdge[i0][0]] <  0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] > 0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] <  0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] >  0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] <  0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] >  0))
+				 ocut =i2;
+				else if   ((dt[i=VerticesOfTriangularEdge[i0][0]] == 0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] >  0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] == 0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] >  0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] == 0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] >  0))
+				 ocut =i2;
+				else if   ((dt[i=VerticesOfTriangularEdge[i0][0]] <  0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] == 0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] <  0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] == 0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] <  0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] == 0))
+				 ocut =i2;
+				else { //  On a edge (2 zero)
+					k =0;
+					if (dt[0]) ocut=0,k++; 
+					if (dt[1]) ocut=1,k++; 
+					if (dt[2]) ocut=2,k++;
+					if(k == 1) {
+						if (dt[ocut] >0) // triangle upper AB
+						 ocut = NextEdge[ocut];
+						i= VerticesOfTriangularEdge[ocut][0];
+						j= VerticesOfTriangularEdge[ocut][1];
+					}
+					else {
+						_error_("Bug Split Edge");
+					}
+				}
+
+				k = OppositeVertex[ocut];
+
+				Icoor2 detbij = bamg::det((*t)[i],(*t)[j],b);
+
+				if (detbij >= 0) { //we find the triangle contening b
+					dt[0]=bamg::det((*t)[1],(*t)[2],b);
+					dt[1]=bamg::det((*t)[2],(*t)[0],b);
+					dt[2]=bamg::det((*t)[0],(*t)[1],b);
+					double dd = t->det;
+					NewItem(t,dt[0]/dd,dt[1]/dd,dt[2]/dd);      
+					return ;}
+				else { // next triangle by  adjacent by edge ocut 
+					deti = dt[i];
+					detj = dt[j];
+					double dij = detj-deti;
+					ba[i] =  detj/dij;
+					ba[j] = -deti/dij;
+					ba[3-i-j ] = 0;
+					ilast=NewItem(t, ba[0],ba[1],ba[2]);      
+
+					AdjacentTriangle ta =t->Adj(ocut);
+					t = ta;
+					iedge= ta; 
+					if (t->det <= 0)  {
+						double ba,bb;
+						AdjacentTriangle edge=CloseBoundaryEdge(b,t,ba,bb);
+						NewItem(B,Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1)));
+						return;
+					}
+				}// we  go outside of omega 
+		} // for(;;)
+	}
+	/*}}}*/
+
+}
Index: /issm/trunk/src/c/bamg/ListofIntersectionTriangles.h
===================================================================
--- /issm/trunk/src/c/bamg/ListofIntersectionTriangles.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/ListofIntersectionTriangles.h	(revision 15396)
@@ -0,0 +1,73 @@
+#ifndef _LISTOFINTERSECTIONTRIANGLES_H_
+#define _LISTOFINTERSECTIONTRIANGLES_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class Triangle;
+
+	class ListofIntersectionTriangles {
+
+		class IntersectionTriangles {
+
+			public: 
+				Triangle *t;
+				double    bary[3];   // use if t != 0
+				R2        x;
+				Metric    m;
+				double    s;         // curvilinear coordinate
+				double    sp;        // length of the previous segment in m
+				double    sn;        // length of the next segment in m
+		};
+
+		class SegInterpolation {
+
+			public:
+				GeomEdge *e;
+				double           sBegin  ,sEnd; // abscisse of the seg on edge parameter
+				double           lBegin  ,lEnd; // length abscisse set in ListofIntersectionTriangles::Length
+				int              last;          // last index in ListofIntersectionTriangles for this Sub seg of edge
+
+				//Methods
+				R2 F(double s){ 
+					double c01=lEnd-lBegin, c0=(lEnd-s)/c01, c1=(s-lBegin)/c01;
+					if (lBegin>s || s>lEnd){
+						_error_("lBegin>s || s>lEnd");
+					}
+					return e->F(sBegin*c0+sEnd*c1);
+				}
+		};
+
+		public:
+
+			int                    MaxSize;
+			int                    Size;
+			double                 len;
+			int                    state;
+			IntersectionTriangles *lIntTria;
+			int                    NbSeg;
+			int                    MaxNbSeg;
+			SegInterpolation      *lSegsI;
+
+			//Constructors/Destructors
+			ListofIntersectionTriangles(int n=256,int m=16);
+			~ListofIntersectionTriangles();
+
+			//Operators
+			IntersectionTriangles & operator[](int i) {return lIntTria[i];}
+			operator int&() {return Size;}
+
+			//Methods
+			void   Init();
+			int    NewItem(Triangle *tt,double d0,double d1,double d2);
+			int    NewItem(R2 ,const Metric &);
+			void   SplitEdge(const Mesh &,const R2 &,const R2 &,int nbegin=0);
+			double Length();
+			long   NewPoints(BamgVertex *,long &nbv,long maxnbv);
+			void   NewSubSeg(GeomEdge *e,double s0,double s1);
+			void   ReShape();
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/Mesh.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Mesh.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/Mesh.cpp	(revision 15396)
@@ -0,0 +1,5848 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../shared/shared.h"
+#include "./bamgobjects.h"
+#include "./det.h"
+
+namespace bamg {
+
+	static const  Direction NoDirOfSearch=Direction();
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Mesh::Mesh(BamgGeom* bamggeom,BamgMesh* bamgmesh, BamgOpts* bamgopts){{{*/
+	Mesh::Mesh(BamgGeom* bamggeom,BamgMesh* bamgmesh, BamgOpts* bamgopts):Gh(*(new Geometry())),BTh(*this){ 
+
+		/*Initialize fields*/
+		Init(0);
+
+		/*Read Geometry if provided*/
+		if(bamggeom->Edges) {
+			Gh.ReadGeometry(bamggeom,bamgopts);
+			Gh.PostRead();
+		}
+
+		/*Read background mesh*/
+		ReadMesh(bamgmesh,bamgopts);
+
+		/*Build Geometry if not provided*/
+		if(bamggeom->Edges==NULL) {
+			/*Recreate geometry if needed*/
+			_printf_("WARNING: mesh present but no geometry found. Reconstructing...\n");
+			BuildGeometryFromMesh(bamgopts);
+			Gh.PostRead();
+		}
+
+		/*Set integer coordinates*/
+		SetIntCoor();
+
+		/*Fill holes and generate mesh properties*/
+		ReconstructExistingMesh();
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::Mesh(int* index,double* x,double* y,int nods,int nels){{{*/
+	Mesh::Mesh(int* index,double* x,double* y,int nods,int nels):Gh(*(new Geometry())),BTh(*this){
+
+		Init(0);
+		ReadMesh(index,x,y,nods,nels);
+		SetIntCoor();
+		ReconstructExistingMesh();
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::Mesh(double* x,double* y,int nods){{{*/
+	Mesh::Mesh(double* x,double* y,int nods):Gh(*(new Geometry())),BTh(*this){
+		Triangulate(x,y,nods);
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::Mesh(const Mesh & Tho,const int *flag ,const int *bb){{{*/
+	Mesh::Mesh(const Mesh & Tho,const int *flag ,const int *bb,BamgOpts* bamgopts) : Gh(*(new Geometry())), BTh(*this) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
+
+		  int i,k,itadj;
+		  int kt=0;
+		  int * kk    = new int [Tho.nbv];
+		  long * reft = new long[Tho.nbt];
+		  long nbInT =    Tho.TriangleReferenceList(reft);
+		  long * refv = new long[Tho.nbv];
+
+		  for (i=0;i<Tho.nbv;i++)
+			kk[i]=-1;
+		  for (i=0;i<Tho.nbv;i++)
+			refv[i]=0;
+		  int nbNewBedge =0;
+		  //  int nbOldBedge =0;  
+		  for (i=0;i<Tho.nbt;i++)
+			if(  reft[i] >=0 && flag[i]) 
+			  {
+				const Triangle & t = Tho.triangles[i];
+				kt++;
+				kk[Tho.GetId(t[0])]=1;
+				kk[Tho.GetId(t[1])]=1;
+				kk[Tho.GetId(t[2])]=1;
+				itadj=Tho.GetId(t.TriangleAdj(0));
+				if (  reft[itadj] >=0 && !flag[itadj])
+				  { nbNewBedge++;
+					refv[Tho.GetId(t[VerticesOfTriangularEdge[0][0]])]=bb[i];
+					refv[Tho.GetId(t[VerticesOfTriangularEdge[0][1]])]=bb[i];
+				  }
+				itadj=Tho.GetId(t.TriangleAdj(1));
+				if (  reft[itadj] >=0 && !flag[itadj])
+				  { nbNewBedge++;
+					refv[Tho.GetId(t[VerticesOfTriangularEdge[1][0]])]=bb[i];
+					refv[Tho.GetId(t[VerticesOfTriangularEdge[1][1]])]=bb[i];}
+					itadj=Tho.GetId(t.TriangleAdj(2));
+					if (  reft[itadj] >=0 && !flag[itadj])
+					  { nbNewBedge++;
+						refv[Tho.GetId(t[VerticesOfTriangularEdge[2][0]])]=bb[i];
+						refv[Tho.GetId(t[VerticesOfTriangularEdge[2][1]])]=bb[i];}
+			  }
+		  k=0;
+		  for (i=0;i<Tho.nbv;i++){
+			  if (kk[i]>=0) kk[i]=k++;
+			}
+		  _printf_("   number of vertices " << k << ", remove = " << Tho.nbv - k << "\n");
+		  _printf_("   number of triangles " << kt << ", remove = " << nbInT-kt << "\n");
+		  _printf_("   number of New boundary edge " << nbNewBedge << "\n");
+		  long imaxnbv =k;
+		  Init(imaxnbv);
+		  for (i=0;i<Tho.nbv;i++)
+			if (kk[i]>=0) 
+			  {
+				vertices[nbv] = Tho.vertices[i];
+				if (!vertices[nbv].GetReferenceNumber())
+				 vertices[nbv].ReferenceNumber = refv[i];
+				nbv++;
+			  }
+		  if (imaxnbv != nbv){
+			  delete [] kk;
+			  delete [] refv;
+			  _error_("imaxnbv != nbv");
+		  }
+		  for (i=0;i<Tho.nbt;i++)
+			if(  reft[i] >=0 && flag[i]) 
+			  {
+				const Triangle & t = Tho.triangles[i];
+				int i0 = Tho.GetId(t[0]);
+				int i1 = Tho.GetId(t[1]);
+				int i2 = Tho.GetId(t[2]);
+				if (i0<0 || i1<0 || i2<0){
+					delete [] refv;
+					_error_("i0<0 || i1<0 || i2< 0");
+				}
+				if (i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv){
+					_error_("i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv");
+				}
+				triangles[nbt] = Triangle(this,kk[i0],kk[i1],kk[i2]);
+				triangles[nbt].color = Tho.subdomains[reft[i]].ReferenceNumber; 
+				nbt++;           
+			  }
+		  if (kt!=nbt){
+			  _error_("kt!=nbt");
+		  }
+		  if (nbt==0 && nbv==0) {
+			  _error_("All triangles have been removed");
+		  }
+		  delete [] kk;
+		  delete [] reft;
+		  delete [] refv;
+		  //double cutoffradian = 10.0/180.0*Pi;
+		  BuildGeometryFromMesh(bamgopts);
+		  Gh.PostRead(); 
+		  SetIntCoor();
+		  ReconstructExistingMesh();
+
+		  if (!nbsubdomains){
+			  _error_("nbsubdomains==0");
+		  }
+		  if (!subdomains[0].head || !subdomains[0].head->link){
+			  _error_("!subdomains[0].head || !subdomains[0].head->link");
+		  }
+
+	  }
+	/*}}}*/
+	/*FUNCTION Mesh::Mesh(Mesh & Th,Geometry * pGh,Mesh * pBth,long maxnbv_in) COPY{{{*/
+	Mesh::Mesh(Mesh & Th,Geometry * pGh,Mesh * pBth,long maxnbv_in)
+	  : Gh(*(pGh?pGh:&Th.Gh)), BTh(*(pBth?pBth:this)) {
+		  /*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
+		  Gh.NbRef++;
+		  maxnbv_in = Max(maxnbv_in,Th.nbv); 
+		  long i;
+		  // do all the allocation to be sure all the pointer existe
+
+		  Init(maxnbv_in);// to make the allocation 
+		  // copy of triangles
+		  nbv = Th.nbv;
+		  nbt = Th.nbt;
+		  nbe = Th.nbe;
+		  nbsubdomains = Th.nbsubdomains;
+		  nbtout = Th.nbtout;
+		  nbq =  Th.nbq ;
+		  NbVerticesOnGeomVertex = Th.NbVerticesOnGeomVertex;
+		  if(NbVerticesOnGeomVertex)
+			VerticesOnGeomVertex = new VertexOnGeom[NbVerticesOnGeomVertex];
+		  NbVerticesOnGeomEdge = Th.NbVerticesOnGeomEdge;
+		  if (NbVerticesOnGeomEdge)
+			VerticesOnGeomEdge = new VertexOnGeom[NbVerticesOnGeomEdge] ;
+		  if (& BTh == & Th.BTh){ // same background 
+			  BTh.NbRef++;
+			  NbVertexOnBThVertex = Th.NbVertexOnBThVertex;
+			  if(NbVertexOnBThVertex)
+				VertexOnBThVertex = new VertexOnVertex[NbVertexOnBThVertex];
+			  NbVertexOnBThEdge = Th.NbVertexOnBThEdge;
+			  if(NbVertexOnBThEdge)
+				VertexOnBThEdge = new VertexOnEdge[NbVertexOnBThEdge];
+			 }
+		  else { // no add on background mesh 
+			  BTh.NbRef++;
+			  NbVertexOnBThVertex=0;
+			  VertexOnBThVertex=0;
+			  NbVertexOnBThEdge=0;
+			  VertexOnBThEdge=0;
+			 }
+
+		  if(nbe)
+			edges = new Edge[nbe];
+		  if(nbsubdomains)
+			subdomains = new SubDomain[nbsubdomains];
+		  pmin = Th.pmin;
+		  pmax = Th.pmax;
+		  coefIcoor = Th.coefIcoor;
+		  for(i=0;i<nbt;i++)
+			triangles[i].Set(Th.triangles[i],Th,*this);
+		  for(i=0;i<nbe;i++)
+			edges[i].Set(Th,i,*this);
+		  for(i=0;i<nbv;i++)
+			vertices[i].Set(Th.vertices[i],Th,*this);
+		  for(i=0;i<nbsubdomains;i++)  
+			subdomains[i].Set(Th,i,*this);
+		  for (i=0;i<NbVerticesOnGeomVertex;i++)
+			VerticesOnGeomVertex[i].Set(Th.VerticesOnGeomVertex[i],Th,*this);
+		  for (i=0;i<NbVerticesOnGeomEdge;i++)
+			VerticesOnGeomEdge[i].Set(Th.VerticesOnGeomEdge[i],Th,*this);
+		  quadtree=0;
+
+	  }
+	/*}}}*/
+	/*FUNCTION Mesh::Mesh(long maxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices){{{*/
+	Mesh::Mesh(long imaxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices) :Gh(BT.Gh),BTh(BT) {
+		this->Init(imaxnbv);
+		TriangulateFromGeom1(bamgopts,keepBackVertices);
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::Mesh(long maxnbv,Geometry & G,BamgOpts* bamgopts){{{*/
+	Mesh::Mesh(long imaxnbv,Geometry & G,BamgOpts* bamgopts):Gh(G),BTh(*this){
+		Init(imaxnbv);
+		TriangulateFromGeom0(bamgopts);
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::~Mesh(){{{*/
+	Mesh::~Mesh() {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
+
+		//if (vertices)             delete [] vertices;
+		if (edges)                delete [] edges;
+		if (triangles)            delete [] triangles;
+		if (quadtree)             delete    quadtree;
+		//if (orderedvertices)                delete [] orderedvertices;
+		if (subdomains)           delete []  subdomains;
+		if (VerticesOnGeomEdge)   delete [] VerticesOnGeomEdge;
+		if (VerticesOnGeomVertex) delete [] VerticesOnGeomVertex;
+		if (VertexOnBThVertex)    delete [] VertexOnBThVertex;
+		if (VertexOnBThEdge)      delete [] VertexOnBThEdge;
+
+		if (&Gh) {
+			if (Gh.NbRef>0) Gh.NbRef--;
+			else if (Gh.NbRef==0) delete &Gh;
+		}
+		if (&BTh && (&BTh != this)) {
+			if (BTh.NbRef>0) BTh.NbRef--;
+			else if (BTh.NbRef==0) delete &BTh;
+		}
+		Init(0); // set all to zero 
+	}
+	/*}}}*/
+
+	/*IO*/
+	/*FUNCTION Mesh::ReadMesh(int* index,double* x,double* y,int nods,int nels){{{*/
+	void Mesh::ReadMesh(int* index,double* x,double* y,int nods,int nels){
+
+		double Hmin = HUGE_VAL;// the infinie value 
+		long i1,i2,i3;
+		long i;
+		Metric M1(1);
+		int verbose=0;
+		bool* nodeflags=NULL;
+
+		nbv=nods;
+		maxnbv=nbv;
+		nbt=nels;
+
+		//Vertices
+		if (verbose) _printf_("Reading vertices (" << nbv << ")\n");
+		vertices=xNew<BamgVertex>(nbv);
+		orderedvertices=xNew<BamgVertex*>(nbv);
+		for (i=0;i<nbv;i++){
+			vertices[i].r.x=x[i];
+			vertices[i].r.y=y[i];
+			vertices[i].ReferenceNumber=1;
+			vertices[i].DirOfSearch =NoDirOfSearch;
+			vertices[i].m=M1;
+			vertices[i].color=0;
+		}
+		maxnbt=2*maxnbv-2; // for filling The Holes and quadrilaterals 
+
+		//Triangles
+		if (verbose) _printf_("Reading triangles (" << nbt << ")\n");
+		triangles =new Triangle[maxnbt]; //we cannot allocate only nbt triangles since 
+		nodeflags=xNew<bool>(nbv);
+		for(i=0;i<nbv;i++) nodeflags[i]=false;
+		//other triangles will be added for each edge
+		for (i=0;i<nbt;i++){
+			Triangle & t = triangles[i];
+			i1=(long)index[i*3+0]-1; //for C indexing
+			i2=(long)index[i*3+1]-1; //for C indexing
+			i3=(long)index[i*3+2]-1; //for C indexing
+			t=Triangle(this,i1,i2,i3);
+			t.color=1;
+			nodeflags[i1]=nodeflags[i2]=nodeflags[i3]=true;
+		}
+
+		/*Recreate geometry: */
+		if (verbose) _printf_("Building Geometry\n");
+		BuildGeometryFromMesh();
+		if (verbose) _printf_("Completing geometry\n");
+		Gh.PostRead();
+
+		/*Check that there is no orphan*/
+		bool isorphan=false;
+		for(i=0;i<nbv;i++){
+			if(!nodeflags[i]){
+				_printf_("Vertex " << i+1 << " does not belong to any element\n");
+				isorphan=true;
+			}
+		}
+		if(isorphan) _error_("Orphan found in mesh, see ids above");
+
+		/*Clean up*/
+		xDelete<bool>(nodeflags);
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts){{{*/
+	void Mesh::ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts){
+
+		int    verbose;
+		double Hmin = HUGE_VAL;    // the infinie value
+		long   i1,i2,i3;
+		long   i,j;
+		Metric M1(1);
+
+		verbose=bamgopts->verbose;
+
+		nbv=bamgmesh->VerticesSize[0];
+		maxnbv=nbv;
+		nbt=bamgmesh->TrianglesSize[0];
+
+		//Vertices
+		if(bamgmesh->Vertices){
+			if(verbose>5) _printf_("      processing Vertices\n");
+
+			vertices=xNew<BamgVertex>(nbv);
+			orderedvertices=xNew<BamgVertex*>(nbv);
+
+			for (i=0;i<nbv;i++){
+				vertices[i].r.x=bamgmesh->Vertices[i*3+0];
+				vertices[i].r.y=bamgmesh->Vertices[i*3+1];
+				vertices[i].ReferenceNumber=(long)bamgmesh->Vertices[i*3+2];
+				vertices[i].DirOfSearch =NoDirOfSearch;
+				vertices[i].m=M1;
+				vertices[i].color=0;
+			}
+			maxnbt=2*maxnbv-2; // for filling The Holes and quadrilaterals 
+		}
+		else{
+			if(verbose>5) _error_("no Vertices found in the initial mesh");
+		}
+
+		//Triangles
+		if(bamgmesh->Triangles){
+			if(verbose>5) _printf_("      processing Triangles\n");
+			triangles =new Triangle[maxnbt]; //we cannot allocate only nbt triangles since 
+			//other triangles will be added for each edge
+			for (i=0;i<nbt;i++){
+				Triangle &t=triangles[i];
+				i1=(long)bamgmesh->Triangles[i*4+0]-1; //for C indexing
+				i2=(long)bamgmesh->Triangles[i*4+1]-1; //for C indexing
+				i3=(long)bamgmesh->Triangles[i*4+2]-1; //for C indexing
+				t=Triangle(this,i1,i2,i3);
+				t.color=(long)bamgmesh->Triangles[i*4+3];
+			}
+		}
+		else{
+			if(verbose>5) _error_("no Triangles found in the initial mesh");
+		}
+
+		//Quadrilaterals
+		if(bamgmesh->Quadrilaterals){
+			if(verbose>5) _printf_("      processing Quadrilaterals\n");
+			long i1,i2,i3,i4;
+			triangles =new Triangle[nbt];
+			for (i=0;i<bamgmesh->QuadrilateralsSize[0];i++){
+				//divide the quad into two triangles
+				Triangle & t1 = triangles[2*i];
+				Triangle & t2 = triangles[2*i+1];
+				i1=(long)bamgmesh->Quadrilaterals[i*5+0]-1; //for C indexing
+				i2=(long)bamgmesh->Quadrilaterals[i*5+1]-1; //for C indexing
+				i3=(long)bamgmesh->Quadrilaterals[i*5+2]-1; //for C indexing
+				i4=(long)bamgmesh->Quadrilaterals[i*5+3]-1; //for C indexing
+				t1=Triangle(this,i1,i2,i3);
+				t2=Triangle(this,i3,i4,i1);
+				t1.color=(long)bamgmesh->Quadrilaterals[i*5+4];
+				t2.color=(long)bamgmesh->Quadrilaterals[i*5+4];
+				t1.SetHidden(OppositeEdge[1]); // two times  because the adj was not created 
+				t2.SetHidden(OppositeEdge[1]); 
+			}
+		}
+
+		//VerticesOnGeomEdge
+		if(bamgmesh->VerticesOnGeomEdge){
+			if(verbose>5) _printf_("      processing VerticesOnGeomEdge\n");
+			NbVerticesOnGeomEdge=bamgmesh->VerticesOnGeomEdgeSize[0];
+			VerticesOnGeomEdge= new  VertexOnGeom[NbVerticesOnGeomEdge] ;
+			for (i=0;i<NbVerticesOnGeomEdge;i++){
+				long  i1,i2;
+				double s;
+				i1=(long)  bamgmesh->VerticesOnGeomEdge[i*3+0]-1; //for C indexing
+				i2=(long)  bamgmesh->VerticesOnGeomEdge[i*3+1]-1; //for C indexing
+				s =(double)bamgmesh->VerticesOnGeomEdge[i*3+2];
+				VerticesOnGeomEdge[i]=VertexOnGeom(vertices[i1],Gh.edges[i2],s);
+			}
+		}
+
+		//VerticesOnGeomVertex
+		if(bamgmesh->VerticesOnGeomVertexSize[0]){
+			if(verbose>5) _printf_("      processing VerticesOnGeomVertex\n");
+			NbVerticesOnGeomVertex=bamgmesh->VerticesOnGeomVertexSize[0];
+			VerticesOnGeomVertex  = new  VertexOnGeom[NbVerticesOnGeomVertex] ;
+			for (i=0;i<NbVerticesOnGeomVertex;i++){
+				long  i1,i2;
+				i1=(long)bamgmesh->VerticesOnGeomVertex[i*2+0]-1; //for C indexing
+				i2=(long)bamgmesh->VerticesOnGeomVertex[i*2+1]-1; //for C indexing
+				VerticesOnGeomVertex[i]=VertexOnGeom(vertices[i1],Gh.vertices[i2]);
+			}
+		}
+
+		//Edges
+		if (bamgmesh->Edges){
+			int i1,i2;
+			double* len=NULL;
+
+			if(verbose>5) _printf_("      processing Edges\n");
+			nbe=bamgmesh->EdgesSize[0];
+			edges= new Edge[nbe];
+			//initialize length of each edge (used to provided metric)
+			len= new double[nbv];
+			for(i=0;i<nbv;i++) len[i]=0;
+
+			for (i=0;i<nbe;i++){
+				i1=(int)bamgmesh->Edges[i*3+0]-1; //-1 for C indexing
+				i2=(int)bamgmesh->Edges[i*3+1]-1; //-1 for C indexing
+				edges[i].ReferenceNumber=(long)bamgmesh->Edges[i*3+2];
+				edges[i].v[0]= vertices +i1;
+				edges[i].v[1]= vertices +i2;
+				edges[i].adj[0]=NULL;
+				edges[i].adj[1]=NULL;
+				R2 x12=vertices[i2].r-vertices[i1].r;
+				double l12=sqrt((x12,x12));
+
+				//prepare metric
+				vertices[i1].color++;
+				vertices[i2].color++;
+				len[i1]+=l12;
+				len[i2]+=l12;
+				Hmin = Min(Hmin,l12);
+			}
+
+			// definition  the default of the given mesh size 
+			for (i=0;i<nbv;i++){
+				if (vertices[i].color>0) 
+				 vertices[i].m=Metric(len[i]/(double)vertices[i].color);
+				else 
+				 vertices[i].m=Metric(Hmin);
+			}
+			delete [] len;
+
+			// construction of edges[].adj 
+			for (i=0;i<nbv;i++){ 
+				vertices[i].color=(vertices[i].color ==2) ?-1:-2;
+			}
+			for (i=0;i<nbe;i++){
+				for (j=0;j<2;j++) { 
+					BamgVertex *v=edges[i].v[j];
+					long i0=v->color,j0;
+					if(i0==-1){
+						v->color=i*2+j;
+					}
+					else if (i0>=0) {// i and i0 edge are adjacent by the vertex v
+						j0 = i0%2;
+						i0 = i0/2;
+						_assert_(v==edges[i0 ].v[j0]);
+						edges[i ].adj[j ] =edges +i0;
+						edges[i0].adj[j0] =edges +i ;
+						v->color = -3;
+					}
+				}
+			}
+		}
+
+		//EdgeOnGeomEdge
+		if(bamgmesh->EdgesOnGeomEdge){
+			if(verbose>5) _printf_("      processing EdgesOnGeomEdge\n");
+			int i1,i2,i,j;
+			i2=bamgmesh->EdgesOnGeomEdgeSize[0];
+			for (i1=0;i1<i2;i1++) {
+				i=(int)bamgmesh->EdgesOnGeomEdge[i1*2+0]-1; //C indexing
+				j=(int)bamgmesh->EdgesOnGeomEdge[i1*2+1]-1; //C indexing
+				//Check value
+				if(!(i>=0 && j>=0 && i<nbe && j<Gh.nbe)) {
+					_error_("ReadMesh error: EdgesOnGeomEdge edge provided (line " << i1+1 << ": [" << i+1 << " " << j+1 << "]) is incorrect (must be positive, [0<i<nbe=" << nbe << " 0<j<Gh.nbe=" << Gh.nbe << "]");
+				}
+				edges[i].GeomEdgeHook=Gh.edges+j;
+			}
+		}
+
+		//SubDomain
+		if(bamgmesh->SubDomains){
+			long i3,head,direction;
+			if(verbose>5) _printf_("      processing SubDomains\n");
+			nbsubdomains=bamgmesh->SubDomainsSize[0];
+			subdomains = new SubDomain [ nbsubdomains ];
+			for (i=0;i<nbsubdomains;i++) {
+				i3  =(int)bamgmesh->SubDomains[i*3+0];
+				head=(int)bamgmesh->SubDomains[i*3+1]-1;//C indexing
+				direction=(int)bamgmesh->SubDomains[i*3+2];
+				if (i3!=23) _error_("Bad Subdomain definition: first number should be 3");
+				if (head<0 || head>=nbt) _error_("Bad Subdomain definition: head should in [1 " << nbt << "] (triangle number)");
+				subdomains[i].head = triangles+head;
+			}
+		}
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::WriteMesh {{{*/
+	void Mesh::WriteMesh(BamgMesh* bamgmesh,BamgOpts* bamgopts){
+
+		/*Intermediary*/
+		int i,j,k,num,i1,i2;
+		long n;
+		int* head_1=NULL;
+		int* next_1=NULL;
+		int* connectivitysize_1=NULL;
+		int  connectivitymax_1=0;
+
+		/*Get options*/
+		int verbose=bamgopts->verbose;
+
+		/*Build reft that holds the number the subdomain number of each triangle, and the real numbering of the elements*/
+		long* reft = new long[nbt];
+		long* numt = new long[nbt];
+		long nbInT = TriangleReferenceList(reft);
+		TriangleIntNumbering(numt);
+
+		/*Chaining algorithm used to generate connectivity tables and other outputs*/
+
+		//Memory Allocation
+		head_1=xNew<int>(nbv);
+		next_1=xNew<int>(3*nbt);
+		connectivitysize_1=xNew<int>(nbv);
+
+		//Initialization
+		for (i=0;i<nbv;i++) head_1[i]=-1;
+		for (i=0;i<nbv;i++) connectivitysize_1[i]=0;
+		k=0;
+		//Chains generation
+		for (i=0;i<nbt;i++) {
+			//Do not take into account outside triangles (reft<0)
+			if (reft[i]>=0){
+				for (j=0;j<3;j++){
+					int v=GetId(triangles[i][j]); //jth vertex of the ith triangle
+					if (k>3*nbt-1 || k<0) _error_("k = " << k << ", nbt = " << nbt);
+					next_1[k]=head_1[v];
+					if (v>nbv-1 || v<0)   _error_("v = " << v << ", nbv = " << nbv);
+					head_1[v]=k++;
+					connectivitysize_1[v]+=1;
+				}
+			}
+		}
+		//Get maximum connectivity
+		connectivitymax_1=0;
+		for (i=0;i<nbv;i++){
+			if (connectivitysize_1[i]>connectivitymax_1) connectivitymax_1=connectivitysize_1[i];
+		}
+
+		/*OK, now build outputs*/
+
+		/*Vertices*/
+		if(verbose>5) _printf_("      writing Vertices\n");
+		bamgmesh->VerticesSize[0]=nbv;
+		bamgmesh->VerticesSize[1]=3;
+		if (nbv){
+			bamgmesh->Vertices=xNew<double>(3*nbv);
+			for (i=0;i<nbv;i++){
+				bamgmesh->Vertices[i*3+0]=vertices[i].r.x;
+				bamgmesh->Vertices[i*3+1]=vertices[i].r.y;
+				bamgmesh->Vertices[i*3+2]=vertices[i].GetReferenceNumber();
+			}
+		}
+
+		/*Edges*/
+		if(verbose>5) _printf_("      writing Edges\n");
+		bamgmesh->EdgesSize[0]=nbe;
+		bamgmesh->EdgesSize[1]=3;
+		int NumIssmSegments=0;
+		if (nbe){
+			bamgmesh->Edges=xNew<double>(3*nbe);
+			for (i=0;i<nbe;i++){
+				bamgmesh->Edges[i*3+0]=GetId(edges[i][0])+1; //back to M indexing
+				bamgmesh->Edges[i*3+1]=GetId(edges[i][1])+1; //back to M indexing
+				bamgmesh->Edges[i*3+2]=edges[i].ReferenceNumber;
+				if(edges[i].GeomEdgeHook){
+					NumIssmSegments++;
+				}
+			}
+		}
+
+		/*Element edges*/
+		if(verbose>5) _printf_("      writing element edges\n");
+		SetOfEdges4* edge4=new SetOfEdges4(nbt*3,nbv);
+		double* elemedge=NULL;
+		elemedge=xNew<double>(3*nbt);
+		for (i=0;i<3*nbt;i++) elemedge[i]=-2.;//will become -1
+		k=0;
+		for (i=0;i<nbt;i++){
+			//Do not take into account outside triangles (reft<0)
+			if (reft[i]>=0){
+				for  (j=0;j<3;j++) {
+					i1=GetId(triangles[i][VerticesOfTriangularEdge[j][0]]);
+					i2=GetId(triangles[i][VerticesOfTriangularEdge[j][1]]);
+					n =edge4->SortAndFind(i1,i2);
+					if (n==-1){
+						//first time
+						n=edge4->SortAndAdd(i1,i2);
+						elemedge[n*2+0]=double(k);
+					}
+					else{
+						//second time
+						elemedge[n*2+1]=double(k);
+					}
+				}
+				k++;
+			}
+		}
+		bamgmesh->IssmEdgesSize[0]=edge4->nb();
+		bamgmesh->IssmEdgesSize[1]=4;
+		bamgmesh->IssmEdges=xNew<double>(4*edge4->nb());
+		for (i=0;i<edge4->nb();i++){
+			/*Invert first two vertices if necessary*/
+			bool found=false;
+			for (j=0;j<3;j++){
+				if (triangles[(int)elemedge[2*i+0]](j)==vertices+edge4->i(i)){
+					if (triangles[(int)elemedge[2*i+0]]((j+1)%3)==vertices+edge4->j(i)){
+						//trigonometric direction
+						bamgmesh->IssmEdges[i*4+0]=edge4->i(i)+1;// back to M indexing
+						bamgmesh->IssmEdges[i*4+1]=edge4->j(i)+1;// back to M indexing
+					}
+					else{
+						bamgmesh->IssmEdges[i*4+0]=edge4->j(i)+1;// back to M indexing
+						bamgmesh->IssmEdges[i*4+1]=edge4->i(i)+1;// back to M indexing
+					}
+					found=true;
+					break;
+				}
+			}
+			_assert_(found);
+			bamgmesh->IssmEdges[i*4+2]=elemedge[2*i+0]+1; // back to M indexing
+			bamgmesh->IssmEdges[i*4+3]=elemedge[2*i+1]+1; // back to M indexing
+		}
+		//clean up
+		delete edge4;
+		xDelete<double>(elemedge);
+
+		/*IssmSegments*/
+		if(verbose>5) _printf_("      writing IssmSegments\n");
+		bamgmesh->IssmSegmentsSize[0]=NumIssmSegments;
+		bamgmesh->IssmSegmentsSize[1]=4;
+		bamgmesh->IssmSegments=xNew<double>(4*NumIssmSegments);
+		num=0;
+		for (i=0;i<nbe;i++){
+			if(edges[i].GeomEdgeHook){
+				//build segment
+				int i1=GetId(edges[i][0]);
+				int i2=GetId(edges[i][1]);
+				bool stop=false;
+				for(j=head_1[i1];j!=-1;j=next_1[j]){
+					for(k=0;k<3;k++){
+						if (GetId(triangles[(int)j/3][k])==i1){
+							if (GetId(triangles[(int)j/3][(int)((k+1)%3)])==i2){
+								bamgmesh->IssmSegments[num*4+0]=GetId(edges[i][0])+1; //back to M indexing
+								bamgmesh->IssmSegments[num*4+1]=GetId(edges[i][1])+1; //back to M indexing
+								bamgmesh->IssmSegments[num*4+2]=(int)j/3+1;            //back to M indexing
+								bamgmesh->IssmSegments[num*4+3]=edges[i].ReferenceNumber;
+								num+=1;
+								stop=true;
+								break;
+							}
+							if (GetId(triangles[(int)j/3][(int)((k+2)%3)])==i2){
+								bamgmesh->IssmSegments[num*4+0]=GetId(edges[i][1])+1; //back to M indexing
+								bamgmesh->IssmSegments[num*4+1]=GetId(edges[i][0])+1; //back to M indexing
+								bamgmesh->IssmSegments[num*4+2]=(int)j/3+1;            //back to M indexing
+								bamgmesh->IssmSegments[num*4+3]=edges[i].ReferenceNumber;
+								num+=1;
+								stop=true;
+								break;
+							}
+						}
+					}
+					if(stop) break;
+				}
+				if (!stop){
+					_error_("Element holding segment [" << i1+1 << " " << i2+1 << "] not found...");
+				}
+			}
+		}
+
+		/*Triangles*/
+		if(verbose>5) _printf_("      writing Triangles\n");
+		k=nbInT-nbq*2;
+		num=0;
+		bamgmesh->TrianglesSize[0]=k;
+		bamgmesh->TrianglesSize[1]=4;
+		if (k){
+			bamgmesh->Triangles=xNew<double>(4*k);
+			for (i=0;i<nbt;i++){
+				Triangle &t=triangles[i];
+				//reft[i]=-1 for outside triangle
+				if (reft[i]>=0 && !( t.Hidden(0) || t.Hidden(1) || t.Hidden(2) )){
+					bamgmesh->Triangles[num*4+0]=GetId(t[0])+1; //back to M indexing
+					bamgmesh->Triangles[num*4+1]=GetId(t[1])+1; //back to M indexing
+					bamgmesh->Triangles[num*4+2]=GetId(t[2])+1; //back to M indexing
+					bamgmesh->Triangles[num*4+3]=subdomains[reft[i]].ReferenceNumber;
+					num=num+1;
+				}
+			}
+		}
+
+		/*Quadrilaterals*/
+		if(verbose>5) _printf_("      writing Quadrilaterals\n");
+		bamgmesh->QuadrilateralsSize[0]=nbq;
+		bamgmesh->QuadrilateralsSize[1]=5;
+		if (nbq){
+			bamgmesh->Quadrilaterals=xNew<double>(5*nbq);
+			for (i=0;i<nbt;i++){
+				Triangle &t =triangles[i];
+				Triangle* ta;
+				BamgVertex *v0,*v1,*v2,*v3;
+				if (reft[i]<0) continue;
+				if ((ta=t.Quadrangle(v0,v1,v2,v3)) !=0 && &t<ta) { 
+					bamgmesh->Quadrilaterals[i*5+0]=GetId(v0)+1; //back to M indexing
+					bamgmesh->Quadrilaterals[i*5+1]=GetId(v1)+1; //back to M indexing
+					bamgmesh->Quadrilaterals[i*5+2]=GetId(v2)+1; //back to M indexing
+					bamgmesh->Quadrilaterals[i*5+3]=GetId(v3)+1; //back to M indexing
+					bamgmesh->Quadrilaterals[i*5+4]=subdomains[reft[i]].ReferenceNumber;
+				}
+			}
+		}
+
+		/*SubDomains*/
+		if(verbose>5) _printf_("      writing SubDomains\n");
+		bamgmesh->SubDomainsSize[0]=nbsubdomains;
+		bamgmesh->SubDomainsSize[1]=4;
+		if (nbsubdomains){
+			bamgmesh->SubDomains=xNew<double>(4*nbsubdomains);
+			for (i=0;i<nbsubdomains;i++){
+				bamgmesh->SubDomains[i*4+0]=3;
+				bamgmesh->SubDomains[i*4+1]=reft[GetId(subdomains[i].head)];
+				bamgmesh->SubDomains[i*4+2]=1;
+				bamgmesh->SubDomains[i*4+3]=subdomains[i].ReferenceNumber;
+			}
+		}
+
+		/*SubDomainsFromGeom*/
+		if(verbose>5) _printf_("      writing SubDomainsFromGeom\n");
+		bamgmesh->SubDomainsFromGeomSize[0]=Gh.nbsubdomains;
+		bamgmesh->SubDomainsFromGeomSize[1]=4;
+		if (Gh.nbsubdomains){
+			bamgmesh->SubDomainsFromGeom=xNew<double>(4*Gh.nbsubdomains);
+			for (i=0;i<Gh.nbsubdomains;i++){
+				bamgmesh->SubDomainsFromGeom[i*4+0]=2;
+				bamgmesh->SubDomainsFromGeom[i*4+1]=GetId(subdomains[i].edge)+1; //back to Matlab indexing
+				bamgmesh->SubDomainsFromGeom[i*4+2]=subdomains[i].direction;
+				bamgmesh->SubDomainsFromGeom[i*4+3]=Gh.subdomains[i].ReferenceNumber;
+			}
+		}
+
+		/*VerticesOnGeomVertex*/
+		if(verbose>5) _printf_("      writing VerticesOnGeomVertex\n");
+		bamgmesh->VerticesOnGeomVertexSize[0]=NbVerticesOnGeomVertex;
+		bamgmesh->VerticesOnGeomVertexSize[1]=2;
+		if (NbVerticesOnGeomVertex){
+			bamgmesh->VerticesOnGeomVertex=xNew<double>(2*NbVerticesOnGeomVertex);
+			for (i=0;i<NbVerticesOnGeomVertex;i++){
+				VertexOnGeom &v=VerticesOnGeomVertex[i];
+				_assert_(v.OnGeomVertex());
+				bamgmesh->VerticesOnGeomVertex[i*2+0]=GetId((BamgVertex*)v)+1; //back to Matlab indexing
+				bamgmesh->VerticesOnGeomVertex[i*2+1]=Gh.GetId((GeomVertex*)v)+1; //back to Matlab indexing
+			}
+		}
+
+		/*VertexOnGeomEdge*/
+		if(verbose>5) _printf_("      writing VerticesOnGeomEdge\n");
+		bamgmesh->VerticesOnGeomEdgeSize[0]=NbVerticesOnGeomEdge;
+		bamgmesh->VerticesOnGeomEdgeSize[1]=3;
+		if (NbVerticesOnGeomEdge){
+			bamgmesh->VerticesOnGeomEdge=xNew<double>(3*NbVerticesOnGeomEdge);
+			for (i=0;i<NbVerticesOnGeomEdge;i++){
+				const VertexOnGeom &v=VerticesOnGeomEdge[i];
+				if (!v.OnGeomEdge()){
+					_error_("A vertices supposed to be OnGeomEdge is actually not");
+				}
+				bamgmesh->VerticesOnGeomEdge[i*3+0]=GetId((BamgVertex*)v)+1; //back to Matlab indexing
+				bamgmesh->VerticesOnGeomEdge[i*3+1]=Gh.GetId((const GeomEdge*)v)+1; //back to Matlab indexing
+				bamgmesh->VerticesOnGeomEdge[i*3+2]=(double)v; //absisce
+			}
+		}
+
+		/*EdgesOnGeomEdge*/
+		if(verbose>5) _printf_("      writing EdgesOnGeomEdge\n");
+		k=0;
+		for (i=0;i<nbe;i++){
+			if (edges[i].GeomEdgeHook) k=k+1;
+		}
+		bamgmesh->EdgesOnGeomEdgeSize[0]=k;
+		bamgmesh->EdgesOnGeomEdgeSize[1]=2;
+		if (k){
+			bamgmesh->EdgesOnGeomEdge=xNew<double>(2*(int)k);
+			int count=0;
+			for (i=0;i<nbe;i++){
+				if (edges[i].GeomEdgeHook){
+					bamgmesh->EdgesOnGeomEdge[count*2+0]=(double)i+1; //back to Matlab indexing
+					bamgmesh->EdgesOnGeomEdge[count*2+1]=(double)Gh.GetId(edges[i].GeomEdgeHook)+1; //back to Matlab indexing
+					count=count+1;
+				}
+			}
+		}
+
+		/*Element Connectivity*/
+		if(verbose>5) _printf_("      writing Element connectivity\n");
+		bamgmesh->ElementConnectivitySize[0]=nbt-nbtout;
+		bamgmesh->ElementConnectivitySize[1]=3;
+		bamgmesh->ElementConnectivity=xNew<double>(3*(nbt-nbtout));
+		for (i=0;i<3*(nbt-nbtout);i++) bamgmesh->ElementConnectivity[i]=NAN;
+		num=0;
+		for (i=0;i<nbt;i++){
+			if (reft[i]>=0){
+				for (j=0;j<3;j++){
+					k=GetId(triangles[i].TriangleAdj(j));
+					if (reft[k]>=0){
+						_assert_(3*num+j<3*(nbt-nbtout));
+						bamgmesh->ElementConnectivity[3*num+j]=k+1; // back to Matlab indexing
+					}
+				}
+				num+=1;
+			}
+		}
+
+		/*ElementNodal Connectivity*/
+		if(verbose>5) _printf_("      writing Nodal element connectivity\n");
+		bamgmesh->NodalElementConnectivitySize[0]=nbv;
+		bamgmesh->NodalElementConnectivitySize[1]=connectivitymax_1;
+		bamgmesh->NodalElementConnectivity=xNew<double>(connectivitymax_1*nbv);
+		for (i=0;i<connectivitymax_1*nbv;i++) bamgmesh->NodalElementConnectivity[i]=NAN;
+		for (i=0;i<nbv;i++){
+			k=0;
+			for(j=head_1[i];j!=-1;j=next_1[j]){
+				_assert_(connectivitymax_1*i+k < connectivitymax_1*nbv);
+				bamgmesh->NodalElementConnectivity[connectivitymax_1*i+k]=floor((double)j/3)+1;
+				k++;
+			}
+		}
+
+		/*Nodal Connectivity*/
+		if(verbose>5) _printf_("      writing Nodal connectivity\n");
+		//chaining algorithm (again...)
+		int* head_2=NULL;
+		int* next_2=NULL;
+		int* connectivitysize_2=NULL;
+		int  connectivitymax_2=0;
+		i1=bamgmesh->IssmEdgesSize[0];
+		i2=bamgmesh->IssmEdgesSize[1];
+		head_2=xNew<int>(nbv);
+		next_2=xNew<int>(2*i1);
+		connectivitysize_2=xNew<int>(nbv);
+		//Initialization
+		for (i=0;i<nbv;i++) head_2[i]=-1;
+		for (i=0;i<nbv;i++) connectivitysize_2[i]=0;
+		k=0;
+		//Chains generation
+		for (i=0;i<i1;i++) {
+			for (j=0;j<2;j++){
+				int v=(int)bamgmesh->IssmEdges[i*i2+j]-1; //back to C indexing
+				if (k>2*i1-1 || k<0) _error_("Index exceed matrix dimensions (k=" << k << " not in [0 " << 2*i1-1 << "]");
+				next_2[k]=head_2[v];
+				if (v>nbv-1 || v<0)   _error_("Index exceed matrix dimensions (v=" << v << " not in [0 " << nbv-1 << "])");
+				head_2[v]=k++;
+				connectivitysize_2[v]+=1;
+			}
+		}
+		//Get maximum connectivity
+		for (i=0;i<nbv;i++){
+			if (connectivitysize_2[i]>connectivitymax_2) connectivitymax_2=connectivitysize_2[i];
+		}
+		//Build output
+		connectivitymax_2++;//add last column for size
+		bamgmesh->NodalConnectivitySize[0]=nbv;
+		bamgmesh->NodalConnectivitySize[1]=connectivitymax_2;
+		bamgmesh->NodalConnectivity=xNew<double>(connectivitymax_2*nbv);
+		for (i=0;i<connectivitymax_2*nbv;i++) bamgmesh->NodalConnectivity[i]=0;
+		for (i=0;i<nbv;i++){
+			k=0;
+			for(j=head_2[i];j!=-1;j=next_2[j]){
+				_assert_(connectivitymax_2*i+k < connectivitymax_2*nbv);
+				num=(int)bamgmesh->IssmEdges[int(j/2)*i2+0];
+				if (i+1==num){ //carefull, ElementEdge is in M indexing
+					//i is the first vertex of the edge, it is therefore connected to the second vertex
+					bamgmesh->NodalConnectivity[connectivitymax_2*i+k]=bamgmesh->IssmEdges[int(j/2)*i2+1];
+				}
+				else{
+					bamgmesh->NodalConnectivity[connectivitymax_2*i+k]=num;
+				}
+				k++;
+			}
+			bamgmesh->NodalConnectivity[connectivitymax_2*(i+1)-1]=k;
+		}
+
+		/*Cracked vertices*/
+		if(verbose>5) _printf_("      writing Cracked vertices\n");
+		bamgmesh->CrackedVerticesSize[0]=NbCrackedVertices;
+		bamgmesh->CrackedVerticesSize[1]=2;
+		if (NbCrackedVertices){
+			bamgmesh->CrackedVertices=xNew<double>(2*NbCrackedVertices);
+			for (i=0;i<NbCrackedVertices;i++){
+				bamgmesh->CrackedVertices[i*2+0]=CrackedVertices[i*2+0]+1; //M indexing
+				bamgmesh->CrackedVertices[i*2+1]=CrackedVertices[i*2+1]+1; //M indexing
+			}
+		}
+
+		/*Cracked vertices*/
+		if(verbose>5) _printf_("      writing Cracked vertices\n");
+		bamgmesh->CrackedEdgesSize[0]=NbCrackedEdges;
+		bamgmesh->CrackedEdgesSize[1]=4;
+		if (NbCrackedEdges){
+			bamgmesh->CrackedEdges=xNew<double>(2*NbCrackedEdges);
+			for (i=0;i<NbCrackedEdges;i++){
+				bamgmesh->CrackedEdges[i*2+0]=0;//CrackedEdges[i]->+1; //M indexing
+				bamgmesh->CrackedEdges[i*2+1]=0;//CrackedEdges[i]-]->+1; //M indexing
+			}
+		}
+
+		//clean up
+		xDelete<int>(connectivitysize_1);
+		xDelete<int>(head_1);
+		xDelete<int>(next_1);
+		xDelete<int>(connectivitysize_2);
+		xDelete<int>(head_2);
+		xDelete<int>(next_2);
+		delete [] reft;
+		delete [] numt;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::ReadMetric{{{*/
+	void Mesh::ReadMetric(const BamgOpts* bamgopts) {
+
+		/*Intermediary*/
+		int  i,j;
+
+		if(bamgopts->verbose>3) _printf_("      processing metric\n");
+		double hmin = Max(bamgopts->hmin,MinimalHmin());
+		double hmax = Min(bamgopts->hmax,MaximalHmax());
+		double coef = bamgopts->coeff;
+
+		//for now we only use j==3
+		j=3;
+
+		for (i=0;i<nbv;i++){
+			double h;
+			if (j == 1){
+				h=bamgopts->metric[i];
+				vertices[i].m=Metric(Max(hmin,Min(hmax, h*coef)));
+			}
+			else if (j==3){
+				//do not erase metric computed by hVertices
+				if (vertices[i].m.a11==1 && vertices[i].m.a21==0 && vertices[i].m.a22==1){
+					double a,b,c;	     
+					a=bamgopts->metric[i*3+0];
+					b=bamgopts->metric[i*3+1];
+					c=bamgopts->metric[i*3+2];
+					Metric M(a,b,c);
+					EigenMetric Vp(M/coef);
+
+					Vp.Maxh(hmax);
+					Vp.Minh(hmin);
+					vertices[i].m = Vp;
+				}
+			}
+		}
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::WriteMetric{{{*/
+	void Mesh::WriteMetric(BamgOpts* bamgopts) {
+		int i;
+		xDelete<double>(bamgopts->metric);
+		bamgopts->metric=xNew<double>(3*nbv);
+		for (i=0;i<nbv;i++){
+			bamgopts->metric[i*3+0]=vertices[i].m.a11;
+			bamgopts->metric[i*3+1]=vertices[i].m.a21;
+			bamgopts->metric[i*3+2]=vertices[i].m.a22;
+		}
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::WriteIndex{{{*/
+	void Mesh::WriteIndex(int** pindex,int* pnels){
+
+		/*Intermediary*/
+		int i,k;
+
+		/*output*/
+		int* index=NULL;
+		int  num=0;
+
+		/*Get number of triangles*/
+		k=0;
+		for (i=0;i<nbt;i++){
+			Triangle &t=triangles[i];
+			if(t.det>0) k++;
+		}
+
+		if (k){
+			index=xNew<int>(3*k);
+			for (i=0;i<nbt;i++){
+				Triangle &t=triangles[i];
+				if (t.det>0 && !(t.Hidden(0)||t.Hidden(1) || t.Hidden(2) )){
+					//if(t.Anisotropy()<2 & t.Length()<1.e+5){
+						index[num*3+0]=GetId(t[0])+1; //back to M indexing
+						index[num*3+1]=GetId(t[1])+1; //back to M indexing
+						index[num*3+2]=GetId(t[2])+1; //back to M indexing
+						num=num+1;
+					//}
+				}
+			}
+		}
+
+		/*Assign output pointers*/
+		*pindex=index;
+		*pnels=num;
+	}
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Mesh::AddGeometryMetric{{{*/
+	void Mesh::AddGeometryMetric(BamgOpts* bamgopts){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectGeomMetric)*/
+
+		/*Get options*/
+		int    verbose=bamgopts->verbose;
+		double anisomax =bamgopts->anisomax;
+		double errg     =bamgopts->errg;
+
+		double ss[2]={0.00001,0.99999};
+		double errC = 2*sqrt(2*errg);
+		double hmax = Gh.MaximalHmax();
+		double hmin = Gh.MinimalHmin();
+
+		//check that hmax is positive
+		if (hmax<=0){
+			_error_("hmax<=0");
+		}
+
+		//errC cannot be higher than 1
+		if (errC>1) errC=1;
+
+		//Set all vertices to "on"
+		SetVertexFieldOn();
+
+		//loop over all the vertices on edges
+		for (int  i=0;i<nbe;i++){
+			for (int j=0;j<2;j++){
+
+				BamgVertex V;
+				VertexOnGeom GV;
+				Gh.ProjectOnCurve(edges[i],ss[j],V,GV);
+
+				GeomEdge* eg = GV;
+				double s = GV;
+				R2 tg;
+				double  R1= eg->R1tg(s,tg);
+				double  ht=hmax;
+				// err relative to the length of the edge
+				if (R1>1.0e-20) {  
+					ht = Min(Max(errC/R1,hmin),hmax);
+				}
+				double hn=Min(hmax,ht*anisomax);
+
+				if (ht<=0 || hn<=0){
+					_error_("ht<=0 || hn<=0");
+				}
+				EigenMetric Vp(1/(ht*ht),1/(hn*hn),tg);
+				Metric MVp(Vp);
+				edges[i][j].m.IntersectWith(MVp);
+			}
+		}
+		// the problem is for the vertex on vertex 
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::AddMetric{{{*/
+	void Mesh::AddMetric(BamgOpts* bamgopts){
+		//  Hessiantype = 0 =>  H is computed using double L2 projection
+		//  Hessiantype = 1 =>  H is computed with green formula
+
+		/*Options*/
+		int Hessiantype=bamgopts->Hessiantype;
+
+		if (Hessiantype==0){
+			BuildMetric0(bamgopts);
+		}
+		else if (Hessiantype==1){
+			BuildMetric1(bamgopts);
+		}
+		else{
+			_error_("Hessiantype " << Hessiantype << " not supported yet (1->use Green formula, 0-> double L2 projection)");
+		}
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::AddVertex{{{*/
+	void Mesh::AddVertex( BamgVertex &s,Triangle* t, Icoor2* det3) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Add)*/
+		// -------------------------------
+		//             s2
+		//                               !
+		//             /|\               !
+		//            / | \              !
+		//           /  |  \             !
+		//    tt1   /   |   \ tt0        !
+		//         /    |s   \           !
+		//        /     .     \          !
+		//       /  .      `   \         !
+		//      / .           ` \        !
+		//      ----------------         !
+		//   s0       tt2       s1
+		//-------------------------------
+
+		/*Intermediaries*/
+		Triangle* tt[3];       //the three triangles
+		Icoor2 det3local[3];   //three determinants (integer)
+		int nbzerodet =0;      //number of zeros in det3
+		int izerodet=-1;       //egde containing the vertex s
+		int iedge; 
+
+		/*three vertices of t*/
+		BamgVertex &s0=(*t)[0];
+		BamgVertex &s1=(*t)[1];
+		BamgVertex &s2=(*t)[2];
+
+		//determinant of t
+		Icoor2 detOld=t->det;
+
+		/* infvertexindex = index of the infinite vertex (NULL)
+			if no infinite vertex (NULL) infvertexindex=-1
+			else if v_i is infinite, infvertexindex=i*/
+		int infvertexindex = &s0 ?  ((  &s1 ? ( &s2  ? -1 : 2) : 1  )) : 0;
+
+		//some checks
+		if (( infvertexindex <0 ) && (detOld <0) ||  ( infvertexindex >=0  ) && (detOld >0) ){
+			_error_("inconsistent configuration (Contact ISSM developers)");
+		}
+
+		// if det3 does not exist, build it 
+		if (!det3){ 
+			//allocate
+			det3 = det3local;
+			//if no infinite vertex
+			if (infvertexindex<0 ) {
+				det3[0]=bamg::det(s ,s1,s2);
+				det3[1]=bamg::det(s0,s ,s2);
+				det3[2]=bamg::det(s0,s1,s );}
+			else { 
+				// one of &s1  &s2  &s0 is NULL
+				det3[0]= &s0 ? -1 : bamg::det(s ,s1,s2) ;
+				det3[1]= &s1 ? -1 : bamg::det(s0,s ,s2) ;
+				det3[2]= &s2 ? -1 : bamg::det(s0,s1,s ) ;
+			}
+		}
+
+		if (!det3[0]) izerodet=0,nbzerodet++;
+		if (!det3[1]) izerodet=1,nbzerodet++;
+		if (!det3[2]) izerodet=2,nbzerodet++;
+
+		//if nbzerodet>0, point s is on an egde or on a vertex 
+		if  (nbzerodet>0){ 
+			/*s is on an edge*/
+			if (nbzerodet==1) {
+				iedge = OppositeEdge[izerodet];
+				AdjacentTriangle ta = t->Adj(iedge);
+
+				/*if the point is one the boundary 
+				  add the point in outside part */
+				if (t->det>=0){ // inside triangle
+					if (((Triangle*)ta)->det<0 ) {
+						// add in outside triangle 
+						AddVertex(s,( Triangle *)ta);
+						return;
+					}
+				}
+			}
+			else{
+				_error_("Cannot add a vertex more than once. Check duplicates");
+			}
+		}
+
+		// remove de MarkUnSwap edge
+		t->SetUnMarkUnSwap(0);
+		t->SetUnMarkUnSwap(1);
+		t->SetUnMarkUnSwap(2);
+
+		tt[0]= t;
+		tt[1]= &triangles[nbt++];
+		tt[2]= &triangles[nbt++];
+
+		if (nbt>maxnbt) _error_("Not enough triangles");
+
+		*tt[1]=*tt[2]=*t;
+		tt[0]->link=tt[1];
+		tt[1]->link=tt[2]; 
+
+		(*tt[0])(OppositeVertex[0])=&s;
+		(*tt[1])(OppositeVertex[1])=&s;
+		(*tt[2])(OppositeVertex[2])=&s;
+
+		tt[0]->det=det3[0];
+		tt[1]->det=det3[1];
+		tt[2]->det=det3[2];         
+
+		//  update adj des triangles externe 
+		tt[0]->SetAdjAdj(0);
+		tt[1]->SetAdjAdj(1);
+		tt[2]->SetAdjAdj(2);
+		//  update des adj des 3 triangle interne
+		const int i0 = 0;
+		const int i1= NextEdge[i0];
+		const int i2 = PreviousEdge[i0];
+
+		tt[i0]->SetAdj2(i2,tt[i2],i0);
+		tt[i1]->SetAdj2(i0,tt[i0],i1);
+		tt[i2]->SetAdj2(i1,tt[i1],i2);
+
+		tt[0]->SetSingleVertexToTriangleConnectivity();
+		tt[1]->SetSingleVertexToTriangleConnectivity();
+		tt[2]->SetSingleVertexToTriangleConnectivity();
+
+		// swap if the point s is on a edge
+		if(izerodet>=0) {
+			int rswap=tt[izerodet]->swap(iedge);
+
+			if (!rswap) {
+				_error_("swap the point s is on a edge");
+			}
+		}
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::BoundAnisotropy{{{*/
+	void  Mesh::BoundAnisotropy(double anisomax,double hminaniso) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/BoundAnisotropy)*/
+
+		long int verbose=0;
+		double lminaniso = 1/ (Max(hminaniso*hminaniso,1e-100));
+
+		//display info
+		if (verbose > 1)  _printf_("   BoundAnisotropy by " << anisomax << "\n");
+
+		double h1=1.e30,h2=1e-30;
+		double coef = 1./(anisomax*anisomax);
+		double hn1=1.e30,hn2=1e-30,rnx =1.e-30,rx=0;  
+
+		//loop over all vertices
+		for (int i=0;i<nbv;i++){
+			EigenMetric Vp(vertices[i]);
+			double lmax=Vp.lmax();
+			Vp*=Min(lminaniso,lmax)/lmax;
+			Vp.BoundAniso2(coef);
+			vertices[i].m = Vp;
+
+			//info to be displayed
+			if (verbose>2){
+				h1 =Min(h1,Vp.lmin());
+				h2 =Max(h2,Vp.lmax());
+				hn1=Min(hn1,Vp.lmin());
+				hn2=Max(hn2,Vp.lmax());
+				rx =Max(rx,Vp.Aniso2());
+				rnx= Max(rnx,Vp.Aniso2());
+			}
+		}
+
+		//display info
+		if (verbose>2){
+			_printf_("      input:  Hmin = " << pow(h2,-0.5)  << ", Hmax = " << pow(h1,-0.5) << ", factor of anisotropy max  = " << pow(rx,0.5) << "\n");
+			_printf_("      output: Hmin = " << pow(hn2,-0.5) << ", Hmax = " << pow(hn1,-0.5)<< ", factor of anisotropy max  = " <<pow(rnx,0.5) << "\n");
+		}
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::BuildGeometryFromMesh{{{*/
+	void Mesh::BuildGeometryFromMesh(BamgOpts* bamgopts){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/ConsGeometry)*/
+
+		/*Reconstruct Geometry from Mesh*/
+
+		/*Intermediary*/
+		int i,j,k,kk,it,jt;
+		int    verbose=0;
+		double cutoffradian=10*Pi/180;
+
+		/*Recover options*/
+		if (bamgopts){
+			verbose=bamgopts->verbose;
+			cutoffradian=bamgopts->MaxCornerAngle*Pi/180;
+		}
+
+		//display info
+		if (verbose>1) _printf_("   construction of the geometry from the 2d mesh\n");
+
+		//check that the mesh is not empty
+		if (nbt<=0 || nbv <=0 ) {
+			_error_("nbt or nbv is negative (Mesh empty?)");
+		}
+
+		//Gh is the geometry of the mesh (this), initialize MaxCornerAngle
+		if (cutoffradian>=0) Gh.MaxCornerAngle = cutoffradian;
+
+		/*Construction of the edges*/
+
+		//initialize st and edge4
+		SetOfEdges4* edge4= new SetOfEdges4(nbt*3,nbv);
+		long*        st   = new long[nbt*3];
+
+		//initialize st as -1 (chaining algorithm)
+		for (i=0;i<nbt*3;i++) st[i]=-1;
+
+		//build edge4 (chain)
+		for (i=0;i<nbe;i++){
+			edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1]));
+		}
+		//check that there is no double edge
+		if (nbe !=  edge4->nb()){ 
+			delete [] st;
+			_error_("Some Double edge in the mesh, the number is " << nbe << ", nbe4=" << edge4->nb()); 
+		}
+		//keep nbe in nbeold
+		long nbeold = nbe;
+
+		//Go through the triangles and ass the edges in edge4 if they are not there yet
+		for (i=0;i<nbt;i++){
+			//3 edges per triangle
+			for  (j=0;j<3;j++) {
+				//Add Edge to edge4 (k=numberofedges in edge4)
+				long k =edge4->SortAndAdd(GetId(triangles[i][VerticesOfTriangularEdge[j][0]]), GetId(triangles[i][VerticesOfTriangularEdge[j][1]]));
+				long invisible = triangles[i].Hidden(j);
+
+				//if st[k] has not been changed yet, add 3*i+j (= vertex position in the index)
+				if(st[k]==-1) st[k]=3*i+j;
+
+				//else st[k]>=0 -> the edge already exist, check
+				else if(st[k]>=0) {
+					//check that it is not an edge on boundary (should not already exist)
+					if (triangles[i].TriangleAdj(j) || triangles[st[k]/3].TriangleAdj((int) (st[k]%3))){
+						_error_("problem in Geometry reconstruction: an edge on boundary is duplicated (double element?)");
+					}
+					//OK, the element is not on boundary, is belongs to 2 triangles -> build Adjacent triangles list
+					triangles[i].SetAdj2(j,triangles + st[k] / 3,(int) (st[k]%3));
+					if (invisible)  triangles[i].SetHidden(j);
+					// if k < nbe mark the edge as on Boundary (Locked)
+					if (k<nbe) {
+						triangles[i].SetLocked(j);
+					}
+					//set st[k] as negative so that the edge should not be called again
+					st[k]=-2-st[k]; 
+				}
+				//else (see 3 lines above), the edge has been called more than twice: return error
+				else {
+					_printf_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << "," << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles (" << k << ")\n");
+					_printf_("Edge " << j << " of triangle " << i << "\n");
+					_printf_("Edge " << (-st[k]+2)%3 << " of triangle " << (-st[k]+2)/3 << "\n");
+					_printf_("Edge " << triangles[(-st[k]+2)/3].NuEdgeTriangleAdj((int)((-st[k]+2)%3)) << " of triangle " << GetId(triangles[(-st[k]+2)/3].TriangleAdj((int)((-st[k]+2)%3))) << "\n");
+					_error_("An edge belongs to more than 2 triangles");
+				}	
+			}
+		}
+
+		//delete edge4
+		long nbedges = edge4->nb(); // the total number of edges 
+		delete edge4; edge4=NULL;
+
+		//display info
+		if(verbose>5) {
+			_printf_("         info on Mesh:\n");
+			_printf_("            - number of vertices    = " << nbv << "\n"); 
+			_printf_("            - number of triangles   = " << nbt << "\n"); 
+			_printf_("            - number of given edges = " << nbe << "\n"); 
+			_printf_("            - number of all edges   = " << nbedges << "\n"); 
+			_printf_("            - Euler number 1 - nb of holes = " << nbt-nbedges+nbv << "\n"); 
+		}
+
+		// check consistency of edge[].adj and geometrical required  vertices
+		k=0; kk=0;
+		for (i=0;i<nbedges;i++){
+			//internal edge
+			if (st[i] <-1) {
+				//get triangle number back
+				it =  (-2-st[i])/3;
+				//get edge position back
+				j  =  (int) ((-2-st[i])%3);
+				Triangle &tt=*triangles[it].TriangleAdj(j);
+				if (triangles[it].color != tt.color|| i < nbeold) k++;
+			}
+			//boundary edge (alone)
+			else if (st[i] >=0) 
+			 kk++;
+		}
+
+		/*Constructions of edges*/
+
+		k += kk;
+		kk=0;
+		if (k) {
+			nbe = k;
+			Edge* edgessave=edges;
+			edges = new Edge[nbe];
+			k =0;
+
+			//display info
+			if(verbose>4) _printf_("   Construction of the edges " << nbe << "\n");
+
+			for (i=0;i<nbedges;i++){ 
+				long  add= -1;
+
+				//internal edge (belongs to two triangles)
+				if (st[i] <-1){ 
+					it =  (-2-st[i])/3;
+					j  =  (int) ((-2-st[i])%3);
+					Triangle & tt = * triangles[it].TriangleAdj(j);
+					if (triangles[it].color !=  tt.color || i < nbeold) add=k++;
+				}
+				//boundary edge
+				else if (st[i] >=0){
+					it = st[i]/3;
+					j  = (int) (st[i]%3);
+					add=k++;
+				}
+				if (add>=0 && add < nbe){
+					edges[add].v[0] = &triangles[it][VerticesOfTriangularEdge[j][0]];
+					edges[add].v[1] = &triangles[it][VerticesOfTriangularEdge[j][1]];
+					edges[add].GeomEdgeHook=NULL; 
+					//if already existed
+					if (i<nbeold){
+						edges[add].ReferenceNumber=edgessave[i].ReferenceNumber; 		      
+						edges[add].GeomEdgeHook=edgessave[i].GeomEdgeHook; //  HACK to get required edges
+						_printf_("oh no...\n");
+					}
+					else
+					 edges[add].ReferenceNumber=Min(edges[add].v[0]->GetReferenceNumber(),edges[add].v[1]->GetReferenceNumber());
+				  }
+			}
+
+			//check that we have been through all edges
+			if (k!=nbe){
+				_error_("problem in edge construction process: k!=nbe (should not happen)");
+			}
+			//delete edgessave
+			if (edgessave) delete [] edgessave;
+		}
+
+		/*Color the vertices*/
+
+		//initialize color of all vertices as 0
+		for (i=0;i<nbv;i++) vertices[i].color =0;
+
+		//go through the edges and add a color to corresponding vertices
+		//(A vertex in 4 edges will have a color 4)
+		for (i=0;i<nbe;i++){
+		 for (j=0;j<2;j++) edges[i].v[j]->color++;
+		}
+
+		//change the color: if a vertex belongs to 2 edges -1, else -2
+		for (i=0;i<nbv;i++) {
+			vertices[i].color=(vertices[i].color ==2)? -1 : -2;
+		}
+
+		/*Build edges[i].adj: adjacency of each edge (if on the same curve)*/
+		for (i=0;i<nbe;i++){
+			for (j=0;j<2;j++){ 
+				//get current vertex
+				BamgVertex* v=edges[i].v[j];
+				//get vertex color (i0)
+				long i0=v->color;
+				long j0;
+
+				//if color<0 (first time), no adjacent edge
+				if(i0<0) edges[i].adj[j]=NULL;
+
+				//if color=-1 (corner),change the vertex color as 2*i+j (position of the vertex in edges)
+				if(i0==-1) v->color=i*2+j;
+
+				//if color>=0 (i and i0 edge are adjacent by the vertex v)
+				else if (i0>=0) {
+					//get position of v in edges back
+					j0 =  i0%2; //column in edges
+					i0 =  i0/2; //line in edges
+
+					//check that we have the correct vertex
+					if (v!=edges[i0 ].v[j0]){
+						_error_("v!=edges[i0 ].v[j0]: this should not happen as the vertex belongs to this edge");
+					}
+
+					//Add adjacence
+					edges[i ].adj[j ]=edges +i0;
+					edges[i0].adj[j0]=edges +i ;
+
+					//change color to -3
+					v->color = -3;
+				}
+			}
+		}
+
+		/*Reconstruct subdomains info*/
+
+		//check that nbsubdomains is empty
+		if (nbsubdomains){
+			_error_("nbsubdomains should be 0");
+		}
+		nbsubdomains=0;
+
+		//color the subdomains
+		long* colorT= new long[nbt];
+		Triangle *tt,*t;
+
+		//initialize the color of each triangle as -1
+		for (it=0;it<nbt;it++) colorT[it]=-1;
+
+		//loop over the triangles
+		for (it=0;it<nbt;it++){
+
+			//if the triangle has not been colored yet:
+			if (colorT[it]<0){
+
+				//color = number of subdomains
+				colorT[it]=nbsubdomains;
+
+				//color all the adjacent triangles of T that share a non marked edge
+				int level =1;
+				int kolor=triangles[it].color;
+				st[0]=it; // stack 
+				st[1]=0;
+				k=1;
+				while (level>0){
+					if( (j=st[level]++)<3 ){ 
+						t = &triangles[st[level-1]];
+						tt=t->TriangleAdj((int)j);
+
+						//color the adjacent triangle
+						if ( ! t->Locked(j) && tt && (colorT[jt = GetId(tt)] == -1) && ( tt->color==kolor)) {
+							colorT[jt]=nbsubdomains;
+							st[++level]=jt;
+							st[++level]=0;
+							k++;
+						}
+					}
+					else level-=2;
+				}
+				nbsubdomains++;
+			}
+		}
+		if (verbose> 3) _printf_("      The Number of sub domain = " << nbsubdomains << "\n"); 
+
+		//build subdomains
+		long isd;
+		subdomains = new SubDomain[nbsubdomains];
+
+		//initialize subdomains[isd].head as 0
+		for (isd=0;isd<nbsubdomains;isd++) subdomains[isd].head =0;
+
+		k=0;
+		for (it=0;it<nbt;it++){
+			for (int j=0;j<3;j++){
+				tt=triangles[it].TriangleAdj(j);
+				if ((!tt || tt->color != triangles[it].color) && !subdomains[isd=colorT[it]].head){
+					subdomains[isd].head = triangles+it;
+					subdomains[isd].ReferenceNumber =  triangles[it].color;
+					subdomains[isd].direction = j; // hack
+					subdomains[isd].edge = 0;
+					k++;
+				}
+			}
+		}
+		//check that we have been through all subdomains
+		if (k!= nbsubdomains){
+			delete [] colorT;
+			_error_("k!= nbsubdomains");
+		}
+		//delete colorT and st
+		delete [] colorT;
+		delete [] st;
+
+		/*Reconstruct Geometry Gh*/
+
+		//build colorV -1 for all vertex and 0 for the vertices belonging to edges
+		long* colorV = new long[nbv];
+		for (i=0;i<nbv;i++) colorV[i]=-1;
+		for (i=0;i<nbe;i++){
+		 for ( j=0;j<2;j++) colorV[GetId(edges[i][j])]=0;
+		}
+		//number the vertices belonging to edges
+		k=0;
+		for (i=0;i<nbv;i++){
+		 if(!colorV[i]) colorV[i]=k++;
+		}
+
+		//Build Gh
+		Gh.nbv=k;
+		Gh.nbe = nbe;
+		Gh.vertices = new GeomVertex[k];
+		Gh.edges = new GeomEdge[nbe];
+		Gh.nbsubdomains = nbsubdomains;
+		Gh.subdomains = new GeomSubDomain[nbsubdomains];
+		if (verbose>3) _printf_("   number of vertices = " << Gh.nbv << "\n   number of edges = " << Gh.nbe << "\n");
+		NbVerticesOnGeomVertex = Gh.nbv;
+		VerticesOnGeomVertex = new VertexOnGeom[NbVerticesOnGeomVertex];
+		NbVerticesOnGeomEdge =0;
+		VerticesOnGeomEdge =0;
+
+		//Build VertexOnGeom
+		for (i=0;i<nbv;i++){
+			if((j=colorV[i])>=0){
+				BamgVertex & v = Gh.vertices[j];
+				v = vertices[i];
+				v.color =0;
+				VerticesOnGeomVertex[j] = VertexOnGeom(vertices[i], Gh.vertices[j]);
+			}
+		}
+
+		//Buid pmin and pmax of Gh (extrema coordinates)
+		Gh.pmin =  Gh.vertices[0].r;
+		Gh.pmax =  Gh.vertices[0].r;
+		// recherche des extrema des vertices pmin,pmax
+		for (i=0;i<Gh.nbv;i++) {
+			Gh.pmin.x = Min(Gh.pmin.x,Gh.vertices[i].r.x);
+			Gh.pmin.y = Min(Gh.pmin.y,Gh.vertices[i].r.y);
+			Gh.pmax.x = Max(Gh.pmax.x,Gh.vertices[i].r.x);
+			Gh.pmax.y = Max(Gh.pmax.y,Gh.vertices[i].r.y);
+		}
+		R2 DD05 = (Gh.pmax-Gh.pmin)*0.05;
+		Gh.pmin -=  DD05;
+		Gh.pmax +=  DD05;
+
+		//Build Gh.coefIcoor
+		Gh.coefIcoor= (MaxICoor)/(Max(Gh.pmax.x-Gh.pmin.x,Gh.pmax.y-Gh.pmin.y));
+		if (Gh.coefIcoor<=0){
+			delete [] colorV;
+			_error_("Gh.coefIcoor<=0 in infered Geometry (this should not happen)");
+		}
+
+		/*Build Gh.edges*/
+
+		//initialize len as 0
+		double * len = new double[Gh.nbv];
+		for(i=0;i<Gh.nbv;i++) len[i]=0;
+
+		//initialize edge4 again
+		edge4= new SetOfEdges4(nbe,nbv);  
+		double hmin = HUGE_VAL;
+		int kreq=0;
+		for (i=0;i<nbe;i++){
+
+			long i0 = GetId(edges[i][0]);
+			long i1 = GetId(edges[i][1]);
+			long j0 = colorV[i0];
+			long j1 = colorV[i1];
+
+			Gh.edges[i].v[0] = Gh.vertices +  j0;
+			Gh.edges[i].v[1] = Gh.vertices +  j1;
+
+			Gh.edges[i].type = 0;
+
+			Gh.edges[i].tg[0]=R2();
+			Gh.edges[i].tg[1]=R2();
+
+			bool required= edges[i].GeomEdgeHook; 
+			if(required) kreq++;
+			edges[i].GeomEdgeHook =  Gh.edges + i;
+			if(required){
+				Gh.edges[i].v[0]->SetRequired();
+				Gh.edges[i].v[1]->SetRequired();
+				Gh.edges[i].SetRequired();
+			}
+
+			R2 x12 = Gh.vertices[j0].r-Gh.vertices[j1].r;
+			double l12=Norme2(x12);        
+			hmin = Min(hmin,l12);
+
+			Gh.vertices[j1].color++;
+			Gh.vertices[j0].color++;
+
+			len[j0]+= l12;
+			len[j1] += l12;
+			hmin = Min(hmin,l12);
+			Gh.edges[i].ReferenceNumber  = edges[i].ReferenceNumber;
+
+			k = edge4->SortAndAdd(i0,i1);
+			if (k != i){
+				delete [] len;
+				delete [] colorV;
+				_error_("problem in Edge4 construction: k != i");
+			}
+		}
+
+		//Build metric for all vertices of Gh
+		for (i=0;i<Gh.nbv;i++){
+		 if (Gh.vertices[i].color > 0) 
+		  Gh.vertices[i].m=  Metric(len[i] /(double) Gh.vertices[i].color);
+		 else 
+		  Gh.vertices[i].m=  Metric(hmin);
+		}
+		//delete len
+		delete [] len;
+
+		//Build Gh.subdomains
+		for (i=0;i<nbsubdomains;i++){
+			it = GetId(subdomains[i].head);
+			j = subdomains[i].direction;
+			long i0 = GetId(triangles[it][VerticesOfTriangularEdge[j][0]]);
+			long i1 = GetId(triangles[it][VerticesOfTriangularEdge[j][1]]);
+			k = edge4->SortAndFind(i0,i1);
+			if(k>=0){
+				subdomains[i].direction = (vertices + i0 == edges[k].v[0]) ? 1 : -1;
+				subdomains[i].edge = edges+k;
+				Gh.subdomains[i].edge = Gh.edges + k;
+				Gh.subdomains[i].direction  =  subdomains[i].direction;
+				Gh.subdomains[i].ReferenceNumber =  subdomains[i].ReferenceNumber;
+			}
+			else
+			 _error_("%i should be >=0");
+		  }
+
+		delete edge4;
+		delete [] colorV;
+
+		//unset adj
+		for (i=0;i<nbt;i++){
+			for ( j=0;j<3;j++){
+				triangles[i].SetAdj2(j,0,triangles[i].GetAllflag(j));
+			}
+		}
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::BuildMetric0 (double L2 projection){{{*/
+	void Mesh::BuildMetric0(BamgOpts* bamgopts){
+
+		/*Options*/
+		double* s=NULL;
+		long    nbsol;
+		int     verbose;
+
+		int   i,j,k,iA,iB,iC;
+		int   iv;
+
+		/*Recover options*/
+		verbose=bamgopts->verbose;
+
+		/*Get and process fields*/
+		s=bamgopts->field;
+		nbsol=bamgopts->fieldSize[1];
+
+		/*Check size*/
+		if (bamgopts->fieldSize[0] != nbv) _error_("'field' should have " << nbv << " rows");
+
+		//initialization of some variables
+		double* ss=(double*)s;
+		double  sA,sB,sC;
+		double*  detT = new double[nbt];
+		double*  sumareas = new double[nbv];
+		double*  alpha= new double[nbt*3];
+		double*  beta = new double[nbt*3];
+		double*  dx_elem    = new double[nbt];
+		double*  dy_elem    = new double[nbt];
+		double*  dx_vertex  = new double[nbv];
+		double*  dy_vertex  = new double[nbv];
+		double*  dxdx_elem  = new double[nbt];
+		double*  dxdy_elem  = new double[nbt];
+		double*  dydy_elem  = new double[nbt];
+		double*  dxdx_vertex= new double[nbv];
+		double*  dxdy_vertex= new double[nbv];
+		double*  dydy_vertex= new double[nbv];
+
+		//display infos
+		if(verbose>1) {
+			_printf_("   Construction of Metric: number of field: " << nbsol << " (nbt=" << nbt << ", nbv=" << nbv << ")\n");
+		}
+
+		//first, build the chains that will be used for the Hessian computation, as weel as the area of each element
+		int* head_s=NULL;
+		head_s=xNew<int>(nbv);
+		int* next_p=NULL;
+		next_p=xNew<int>(3*nbt);
+		int  p=0;
+		//initialization
+		for(i=0;i<nbv;i++){
+			sumareas[i]=0;
+			head_s[i]=-1;
+		}
+		for(i=0;i<nbt;i++){
+
+			//lopp over the real triangles (no boundary elements)
+			if(triangles[i].link){ 
+
+				//get current triangle t
+				const Triangle &t=triangles[i];
+
+				// coor of 3 vertices 
+				R2 A=t[0];
+				R2 B=t[1];
+				R2 C=t[2];
+
+				//compute triangle determinant (2*Area)
+				double dett = bamg::Area2(A,B,C);
+				detT[i]=dett;
+
+				/*The nodal functions are such that for a vertex A:
+				 *    N_A(x,y)=alphaA x + beta_A y +gamma_A
+				 *    N_A(A) = 1,   N_A(B) = 0,   N_A(C) = 0
+				 * solving this system of equation (determinant = 2Area(T) != 0 if A,B and C are not inlined)
+				 * leads to:
+				 *    N_A = (xB yC - xC yB + x(yB-yC) +y(xC-xB))/(2*Area(T))
+				 * and this gives:
+				 *    alpha_A = (yB-yC)/(2*Area(T))*/
+				alpha[i*3+0]=(B.y-C.y)/dett;
+				alpha[i*3+1]=(C.y-A.y)/dett;
+				alpha[i*3+2]=(A.y-B.y)/dett;
+				beta[ i*3+0]=(C.x-B.x)/dett;
+				beta[ i*3+1]=(A.x-C.x)/dett;
+				beta[ i*3+2]=(B.x-A.x)/dett;
+
+				//compute chains
+				for(j=0;j<3;j++){
+					k=GetId(triangles[i][j]);
+					next_p[p]=head_s[k];
+					head_s[k]=p++;
+
+					//add area to sumareas
+					sumareas[k]+=dett;
+				}
+
+			}
+		}
+
+		//for all Solutions
+		for (int nusol=0;nusol<nbsol;nusol++) {
+			double smin=ss[nusol],smax=ss[nusol];
+
+			//get min(s), max(s) and initialize Hessian (dxdx,dxdy,dydy)
+			for ( iv=0,k=0; iv<nbv; iv++){
+				smin=Min(smin,ss[iv*nbsol+nusol]);
+				smax=Max(smax,ss[iv*nbsol+nusol]);
+			}
+			double sdelta=smax-smin;
+			double absmax=Max(Abs(smin),Abs(smax));
+
+			//display info
+			if(verbose>2) _printf_("      Solution " << nusol << ", Min = " << smin << ", Max = " << smax << ", Delta = " << sdelta << "\n");
+
+			//skip constant field
+			if (sdelta < 1.0e-10*Max(absmax,1e-20)){
+				_printf_("      Solution " << nusol << " is constant, skipping...\n");
+				continue;
+			}
+
+			//initialize the hessian and gradient matrices
+			for ( iv=0,k=0; iv<nbv; iv++) dxdx_vertex[iv]=dxdy_vertex[iv]=dydy_vertex[iv]=dx_vertex[iv]=dy_vertex[iv]=0;
+
+			//1: Compute gradient for each element (exact)
+			for (i=0;i<nbt;i++){
+				if(triangles[i].link){
+					// number of the 3 vertices
+					iA = GetId(triangles[i][0]);
+					iB = GetId(triangles[i][1]);
+					iC = GetId(triangles[i][2]);
+
+					// value of the P1 fonction on 3 vertices 
+					sA = ss[iA*nbsol+nusol];
+					sB = ss[iB*nbsol+nusol];
+					sC = ss[iC*nbsol+nusol];
+
+					//gradient = (sum alpha_i s_i, sum_i beta_i s_i)
+					dx_elem[i]=sA*alpha[3*i+0]+sB*alpha[3*i+1]+sC*alpha[3*i+2];
+					dy_elem[i]=sA*beta[ 3*i+0]+sB*beta[ 3*i+1]+sC*beta[ 3*i+2];
+				}
+			}
+
+			//2: then compute a gradient for each vertex using a P2 projection
+			for(i=0;i<nbv;i++){
+				for(p=head_s[i];p!=-1;p=next_p[p]){
+					//Get triangle number
+					k=(long)(p/3);
+					dx_vertex[i]+=dx_elem[k]*detT[k]/sumareas[i];
+					dy_vertex[i]+=dy_elem[k]*detT[k]/sumareas[i];
+				}
+			}
+
+			//3: compute Hessian matrix on each element
+			for (i=0;i<nbt;i++){
+				if(triangles[i].link){
+					// number of the 3 vertices
+					iA = GetId(triangles[i][0]);
+					iB = GetId(triangles[i][1]);
+					iC = GetId(triangles[i][2]);
+
+					//Hessian
+					dxdx_elem[i]=dx_vertex[iA]*alpha[3*i+0]+dx_vertex[iB]*alpha[3*i+1]+dx_vertex[iC]*alpha[3*i+2];
+					dxdy_elem[i]=dy_vertex[iA]*alpha[3*i+0]+dy_vertex[iB]*alpha[3*i+1]+dy_vertex[iC]*alpha[3*i+2];
+					dydy_elem[i]=dy_vertex[iA]*beta[3*i+0]+dy_vertex[iB]*beta[3*i+1]+dy_vertex[iC]*beta[3*i+2];
+				}
+			}
+
+			//4: finaly compute Hessian on each vertex using the second P2 projection
+			for(i=0;i<nbv;i++){
+				for(p=head_s[i];p!=-1;p=next_p[p]){
+					//Get triangle number
+					k=(long)(p/3);
+					dxdx_vertex[i]+=dxdx_elem[k]*detT[k]/sumareas[i];
+					dxdy_vertex[i]+=dxdy_elem[k]*detT[k]/sumareas[i];
+					dydy_vertex[i]+=dydy_elem[k]*detT[k]/sumareas[i];
+				}
+			}
+
+			/*Compute Metric from Hessian*/
+			for ( iv=0;iv<nbv;iv++){
+				vertices[iv].MetricFromHessian(dxdx_vertex[iv],dxdy_vertex[iv],dydy_vertex[iv],smin,smax,ss[iv*nbsol+nusol],bamgopts->err[nusol],bamgopts);
+			}
+
+		}//for all solutions
+
+		//clean up
+		xDelete<int>(head_s);
+		xDelete<int>(next_p);
+		delete [] detT;
+		delete [] alpha;
+		delete [] beta;
+		delete [] sumareas;
+		delete [] dx_elem;
+		delete [] dy_elem;
+		delete [] dx_vertex;
+		delete [] dy_vertex;
+		delete [] dxdx_elem;
+		delete [] dxdy_elem;
+		delete [] dydy_elem;
+		delete [] dxdx_vertex;
+		delete [] dxdy_vertex;
+		delete [] dydy_vertex;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::BuildMetric1 (Green formula){{{*/
+	void Mesh::BuildMetric1(BamgOpts* bamgopts){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectConsMetric)*/
+
+		/*Options*/
+		double* s=NULL;
+		long nbsol;
+		int NbJacobi;
+		int verbose;
+
+		/*Recover options*/
+		verbose=bamgopts->verbose;
+		NbJacobi=bamgopts->nbjacobi;
+
+		/*Get and process fields*/
+		s=bamgopts->field;
+		nbsol=bamgopts->fieldSize[1];
+
+		/*Check size*/
+		if (bamgopts->fieldSize[0] != nbv) _error_("'field' should have " << nbv << " rows");
+
+		//initialization of some variables
+		long    i,k,iA,iB,iC,iv;
+		R2      O(0,0);
+		double* ss=(double*)s;
+		double  sA,sB,sC;
+		double*  detT = new double[nbt];
+		double*  Mmass= new double[nbv];
+		double*  Mmassxx= new double[nbv];
+		double*  dxdx= new double[nbv];
+		double*  dxdy= new double[nbv];
+		double*  dydy= new double[nbv];
+		double*  workT= new double[nbt];
+		double*  workV= new double[nbv];
+		int*    OnBoundary = new int[nbv];
+
+		//display infos
+		if(verbose>1) {
+			_printf_("   Construction of Metric: number of field: " << nbsol << " (nbt=" << nbt << ", nbv=" << nbv << ")\n");
+		}
+
+		//initialize Mmass, OnBoundary and Massxx by zero
+		for (iv=0;iv<nbv;iv++){
+			Mmass[iv]=0;
+			OnBoundary[iv]=0;
+			Mmassxx[iv]=0;
+		}
+
+		//Build detT Mmas Mmassxx workT and OnBoundary
+		for (i=0;i<nbt;i++){ 
+
+			//lopp over the real triangles (no boundary elements)
+			if(triangles[i].link){ 
+
+				//get current triangle t
+				const Triangle &t=triangles[i];
+
+				// coor of 3 vertices 
+				R2 A=t[0];
+				R2 B=t[1];
+				R2 C=t[2];
+
+				// number of the 3 vertices
+				iA = GetId(t[0]);
+				iB = GetId(t[1]);
+				iC = GetId(t[2]);
+
+				//compute triangle determinant (2*Area)
+				double dett = bamg::Area2(A,B,C);
+				detT[i]=dett;
+				dett /= 6;
+
+				// construction of OnBoundary (flag=1 if on boundary, else 0)
+				int nbb=0;
+				for(int j=0;j<3;j++){
+					//get adjacent triangle
+					Triangle *ta=t.Adj(j);
+					//if there is no adjacent triangle, the edge of the triangle t is on boundary
+					if ( !ta || !ta->link){
+						//mark the two vertices of the edge as OnBoundary
+						OnBoundary[GetId(t[VerticesOfTriangularEdge[j][0]])]=1;
+						OnBoundary[GetId(t[VerticesOfTriangularEdge[j][1]])]=1;
+						nbb++;
+					}
+				}
+
+				//number of vertices on boundary for current triangle t
+				workT[i] = nbb;
+
+				//Build Mmass Mmass[i] = Mmass[i] + Area/3
+				Mmass[iA] += dett;
+				Mmass[iB] += dett;
+				Mmass[iC] += dett;
+
+				//Build Massxx = Mmass
+				Mmassxx[iA] += dett;
+				Mmassxx[iB] += dett;
+				Mmassxx[iC] += dett;
+			}
+
+			//else: the triangle is a boundary triangle -> workT=-1
+			else workT[i]=-1;
+		}
+
+		//for all Solution  
+		for (int nusol=0;nusol<nbsol;nusol++) {
+
+			double smin=ss[nusol],smax=ss[nusol];
+			double h1=1.e30,h2=1e-30,rx=0;
+			double hn1=1.e30,hn2=1e-30,rnx =1.e-30;  
+
+			//get min(s), max(s) and initialize Hessian (dxdx,dxdy,dydy)
+			for ( iv=0,k=0; iv<nbv; iv++ ){
+				dxdx[iv]=dxdy[iv]=dydy[iv]=0;
+				smin=Min(smin,ss[iv*nbsol+nusol]);
+				smax=Max(smax,ss[iv*nbsol+nusol]);
+			}
+			double sdelta=smax-smin;
+			double absmax=Max(Abs(smin),Abs(smax));
+
+			//display info
+			if(verbose>2) _printf_("      Solution " << nusol << ", Min = " << smin << ", Max = " << smax << ", Delta = " << sdelta << ", number of fields = " << nbsol << "\n");
+
+			//skip constant field
+			if (sdelta < 1.0e-10*Max(absmax,1e-20) ){
+				if (verbose>2) _printf_("      Solution " << nusol << " is constant, skipping...\n");
+				continue;
+			}
+
+			//pointer toward ss that is also a pointer toward s (solutions)
+			double* sf=ss; 
+
+				//initialize the hessian matrix
+				for ( iv=0,k=0; iv<nbv; iv++) dxdx[iv]=dxdy[iv]=dydy[iv]=0;
+
+				//loop over the triangles
+				for (i=0;i<nbt;i++){
+
+					//for real all triangles 
+					if(triangles[i].link){
+
+						// coor of 3 vertices 
+						R2 A=triangles[i][0];
+						R2 B=triangles[i][1];
+						R2 C=triangles[i][2];
+
+						//warning: the normal is internal and the size is the length of the edge
+						R2 nAB = Orthogonal(B-A);
+						R2 nBC = Orthogonal(C-B);
+						R2 nCA = Orthogonal(A-C);
+						//note that :  nAB + nBC + nCA == 0 
+
+						// number of the 3 vertices
+						iA = GetId(triangles[i][0]);
+						iB = GetId(triangles[i][1]);
+						iC = GetId(triangles[i][2]);
+
+						// for the test of  boundary edge
+						// the 3 adj triangles 
+						Triangle *tBC = triangles[i].TriangleAdj(OppositeEdge[0]);
+						Triangle *tCA = triangles[i].TriangleAdj(OppositeEdge[1]);
+						Triangle *tAB = triangles[i].TriangleAdj(OppositeEdge[2]);
+
+						// value of the P1 fonction on 3 vertices 
+						sA = ss[iA*nbsol+nusol];
+						sB = ss[iB*nbsol+nusol];
+						sC = ss[iC*nbsol+nusol];
+
+						/*The nodal functions are such that for a vertex A:
+						  N_A(x,y)=alphaA x + beta_A y +gamma_A
+						  N_A(A) = 1,   N_A(B) = 0,   N_A(C) = 0
+						  solving this system of equation (determinant = 2Area(T) != 0 if A,B and C are not inlined)
+						  leads to:
+						  N_A = (xB yC - xC yB + x(yB-yC) +y(xC-xB))/(2*Area(T))
+						  and this gives:
+						  alpha_A = (yB-yC)/(2*Area(T))
+						  beta_A = (xC-xB)/(2*Area(T))
+						  and therefore:
+						  grad N_A = nA / detT
+						  for an interpolation of a solution s:
+						  grad(s) = s * sum_{i=A,B,C} grad(N_i) */
+
+						R2 Grads=(nAB*sC+nBC*sA+nCA*sB)/detT[i];
+
+						//Use Green to compute Hessian Matrix
+
+						// if edge on boundary no contribution  => normal = 0
+						if ( !tBC || !tBC->link ) nBC=O;
+						if ( !tCA || !tCA->link ) nCA=O;
+						if ( !tAB || !tAB->link ) nAB=O;
+
+						// remark we forgot a 1/2 because
+						//       int_{edge} w_i = 1/2 if i is in edge 
+						//                         0  if not
+						// if we don't take the  boundary 
+						dxdx[iA] += ( nCA.x + nAB.x ) *Grads.x;
+						dxdx[iB] += ( nAB.x + nBC.x ) *Grads.x;
+						dxdx[iC] += ( nBC.x + nCA.x ) *Grads.x;
+
+						//warning optimization (1) the division by 2 is done on the metric construction
+						dxdy[iA] += (( nCA.y + nAB.y ) *Grads.x + ( nCA.x + nAB.x ) *Grads.y) ;
+						dxdy[iB] += (( nAB.y + nBC.y ) *Grads.x + ( nAB.x + nBC.x ) *Grads.y) ;
+						dxdy[iC] += (( nBC.y + nCA.y ) *Grads.x + ( nBC.x + nCA.x ) *Grads.y) ; 
+
+						dydy[iA] += ( nCA.y + nAB.y ) *Grads.y;
+						dydy[iB] += ( nAB.y + nBC.y ) *Grads.y;
+						dydy[iC] += ( nBC.y + nCA.y ) *Grads.y;
+
+					} // for real all triangles 
+				}
+
+				long kk=0;
+				for ( iv=0,k=0 ; iv<nbv; iv++){
+					if(Mmassxx[iv]>0){
+						dxdx[iv] /= 2*Mmassxx[iv];
+						// warning optimization (1) on term dxdy[iv]*ci/2 
+						dxdy[iv] /= 4*Mmassxx[iv];
+						dydy[iv] /= 2*Mmassxx[iv];
+						// Compute the matrix with abs(eigen value)
+						Metric M(dxdx[iv], dxdy[iv], dydy[iv]);
+						EigenMetric Vp(M);
+						Vp.Abs();
+						M = Vp;
+						dxdx[iv] = M.a11;
+						dxdy[iv] = M.a21;
+						dydy[iv] = M.a22;
+					}
+					else kk++;
+				}
+
+				// correction of second derivative
+				// by a laplacien
+				double* d2[3] = {dxdx, dxdy, dydy};
+				double* dd;
+				for (int xy = 0;xy<3;xy++) {
+					dd = d2[xy];
+					// do leat 2 iteration for boundary problem
+					for (int ijacobi=0;ijacobi<Max(NbJacobi,2);ijacobi++){
+						for (i=0;i<nbt;i++) 
+						 if(triangles[i].link){// the real triangles 
+							 // number of the 3 vertices
+							 iA = GetId(triangles[i][0]);
+							 iB = GetId(triangles[i][1]);
+							 iC = GetId(triangles[i][2]);
+							 double cc=3;
+							 if(ijacobi==0)
+							  cc = Max((double) ((Mmassxx[iA]>0)+(Mmassxx[iB]>0)+(Mmassxx[iC]>0)),1.);
+							 workT[i] = (dd[iA]+dd[iB]+dd[iC])/cc;
+						 }
+						for (iv=0;iv<nbv;iv++) workV[iv]=0;
+
+						for (i=0;i<nbt;i++){ 
+							if(triangles[i].link){ // the real triangles 
+								// number of the 3 vertices
+								iA = GetId(triangles[i][0]);
+								iB = GetId(triangles[i][1]);
+								iC = GetId(triangles[i][2]);
+								double cc =  workT[i]*detT[i];
+								workV[iA] += cc;
+								workV[iB] += cc;
+								workV[iC] += cc;
+							}
+						}
+
+						for (iv=0;iv<nbv;iv++){
+							if( ijacobi<NbJacobi || OnBoundary[iv]){
+								dd[iv] = workV[iv]/(Mmass[iv]*6);
+							}
+						}
+					}
+				}
+
+				/*Compute Metric from Hessian*/
+				for ( iv=0;iv<nbv;iv++){
+					vertices[iv].MetricFromHessian(dxdx[iv],dxdy[iv],dydy[iv],smin,smax,ss[iv*nbsol+nusol],bamgopts->err[nusol],bamgopts);
+				}
+
+		}// end for all solution 
+
+		delete [] detT;
+		delete [] Mmass;
+		delete [] dxdx;
+		delete [] dxdy;
+		delete [] dydy;
+		delete []  workT;
+		delete [] workV;
+		delete [] Mmassxx;
+		delete []  OnBoundary;
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::CrackMesh{{{*/
+	void Mesh::CrackMesh(BamgOpts* bamgopts) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/CrackMesh)*/
+
+		/*Intermediary*/
+		int i,j,k,num,count;
+		int i1,i2;
+		int j1,j2;
+
+		/*Options*/
+		int verbose=bamgopts->verbose;
+
+		//  computed the number of cracked edge
+		for (k=i=0;i<nbe;i++){
+			if(edges[i].GeomEdgeHook->Cracked()) k++;
+		}
+
+		//Return if no edge is cracked
+		if(k==0) return;
+		if (verbose>4) _printf_("      number of Cracked Edges = " << k << "\n");
+
+		//Initialize Cracked edge
+		NbCrackedEdges=k;
+		CrackedEdges=new CrackedEdge[k];
+
+		//Compute number of Cracked Vertices
+		k=0;
+		NbCrackedVertices=0;
+
+		int* splitvertex=new int[nbv];
+		for (i=0;i<nbv;i++) splitvertex[i]=0;
+
+		for (i=0;i<nbe;i++){
+			if(edges[i].GeomEdgeHook->Cracked()){
+
+				//Fill edges fields of CrackedEdges
+				CrackedEdges[k  ].E =edges[i].GeomEdgeHook;
+				CrackedEdges[k++].e1=&edges[i];
+
+				//Get number of the two vertices on the edge
+				i1=GetId(edges[i][0]);
+				i2=GetId(edges[i][1]);
+				_assert_(i1>=0 && i1<nbv && i2>=0 && i2<nbv);
+				splitvertex[i1]++;
+				splitvertex[i2]++;
+
+				//If the vertex has already been flagged once, it is a cracked vertex (tip otherwise)
+				if (splitvertex[i1]==2) NbCrackedVertices++;
+				if (splitvertex[i2]==2) NbCrackedVertices++;
+
+				//The vertex cannot be marked more than twice
+				if (splitvertex[i1]==3 || splitvertex[i2]==3){
+					delete [] splitvertex;
+					_error_("Crossing rifts not supported yet");
+				}
+			}
+		}
+		_assert_(k==NbCrackedEdges);
+
+		//Add new vertices
+		if (verbose>4) _printf_("      number of Cracked Vertices = " << NbCrackedVertices << "\n");
+		if (NbCrackedVertices){
+			CrackedVertices=xNew<long>(2*NbCrackedVertices);
+			num=0;
+			for (i=0;i<nbv;i++){
+				if (splitvertex[i]==2){
+					CrackedVertices[num*2+0]=i;      //index of first vertex
+					CrackedVertices[num*2+1]=nbv+num;//index of new vertex
+					num++;
+				}
+			}
+			_assert_(num==NbCrackedVertices);
+		}
+		delete [] splitvertex;
+
+		//Now, find the triangles that hold a cracked edge
+		CreateSingleVertexToTriangleConnectivity();
+
+		long* Edgeflags=new long[NbCrackedEdges];
+		for(i=0;i<NbCrackedEdges;i++) Edgeflags[i]=0;
+
+		for(i=0;i<NbCrackedEdges;i++){
+			//Get the numbers of the 2 vertices of the crren cracked edge
+			i1=GetId((*CrackedEdges[i].e1)[0]);
+			i2=GetId((*CrackedEdges[i].e1)[1]);
+
+			//find a triangle holding the vertex i1 (first vertex of the ith cracked edge)
+			Triangle* tbegin=vertices[i1].t;
+			k=vertices[i1].IndexInTriangle;//local number of i in triangle tbegin
+			_assert_(GetId((*tbegin)[k])==GetId(vertices[i1]));
+
+			//Now, we are going to go through the adjacent triangle that hold i1 till
+			//we find one that has the cracked edge
+			AdjacentTriangle ta(tbegin,EdgesVertexTriangle[k][0]);
+			count=0;
+			do {
+				for(j=0;j<3;j++){
+					//Find the position of i1 in the triangle index
+					if (GetId((*ta.t)[j])==i1){
+						j1=j;
+						break;
+					}
+				}
+				for(j=0;j<3;j++){
+					//Check wether i2 is also in the triangle index
+					if (GetId((*ta.t)[j])==i2){
+						j2=j;
+						//Invert j1 and j2 if necessary
+						if ((j1+1)%3==j2){
+							int j3=j1;
+							j1=j2;
+							j2=j3;
+						}
+						if (Edgeflags[i]==0){
+							//first element
+							CrackedEdges[i].a=ta.t;
+							CrackedEdges[i].length=Norme2((*ta.t)[j1].r-(*ta.t)[j2].r);
+							CrackedEdges[i].normal=Orthogonal((*ta.t)[j1].r-(*ta.t)[j2].r);
+						}
+						else{
+							//Second element -> to renumber
+							CrackedEdges[i].b=ta.t;
+							CrackedEdges[i].length=Norme2((*ta.t)[j1].r-(*ta.t)[j2].r);
+							CrackedEdges[i].normal=Orthogonal((*ta.t)[j1].r-(*ta.t)[j2].r);
+						}
+						Edgeflags[i]++;
+						break;
+					}
+				}
+				//_printf_(element_renu[GetId(ta.t)] << " -> " << GetId((*ta.t)[0])+1 << " " << GetId((*ta.t)[1])+1 << " " << GetId((*ta.t)[2])+1 << ", edge [" << i1 << "->" << j1 << " " << i2 << "->" << j2 << "]\n");
+				ta = Next(ta).Adj(); 
+				if (count++>50) _error_("Maximum number of iteration exceeded");
+			}while ((tbegin != ta)); 
+		}
+
+		//Check EdgeFlag
+		for(i=0;i<NbCrackedEdges;i++){
+			if (Edgeflags[i]!=2){
+				_error_("A problem occured: at least one crack edge (number " << i+1 << ") does not belong to 2 elements");
+			}
+		}
+		delete [] Edgeflags;
+
+		//Reset BamgVertex to On
+		SetVertexFieldOn();
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::Echo{{{*/
+	void Mesh::Echo(void) {
+
+		int i;
+
+		_printf_("Mesh Echo:\n");
+		_printf_("   nbv = " << nbv << "\n");
+		_printf_("   nbt = " << nbt << "\n");
+		_printf_("   nbe = " << nbe << "\n");
+		_printf_("   nbq = " << nbq << "\n");
+		_printf_("   index:\n");
+		for (i=0;i<nbt;i++){
+			_printf_("   " << setw(4) << i+1 << ": [" 
+						<< setw(4) << (((BamgVertex *)triangles[i](0))?GetId(triangles[i][0])+1:0) << " " 
+						<< setw(4) << (((BamgVertex *)triangles[i](0))?GetId(triangles[i][1])+1:0) << " " 
+						<< setw(4) << (((BamgVertex *)triangles[i](0))?GetId(triangles[i][2])+1:0) << "]");
+		}
+		_printf_("   coordinates:\n");
+		for (i=0;i<nbv;i++){
+			_printf_("   " << setw(4) << i+1 << ": [" << vertices[i].r.x << " " << vertices[i].r.y << "]\n");
+		}
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::ForceBoundary{{{*/
+		void Mesh::ForceBoundary() {
+			/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceBoundary)*/
+
+			long int verbose=2;
+			int k=0;
+			int nbfe=0,nbswp=0,Nbswap=0;
+
+			//display
+			if (verbose > 2) _printf_("   ForceBoundary  nb of edge: " << nbe << "\n");
+
+			//check that there is no triangle with 0 determinant
+			for (int t = 0; t < nbt; t++){
+				if (!triangles[t].det) k++;
+			}
+			if (k!=0) {
+				_error_("there is " << k << " triangles of mes = 0");
+			}
+
+			//Force Edges
+			AdjacentTriangle ta(0,0);
+			for (int i = 0; i < nbe; i++){
+
+				//Force edge i
+				nbswp =  ForceEdge(edges[i][0],edges[i][1],ta);
+				if (nbswp<0) k++;
+				else Nbswap += nbswp;
+
+				if (nbswp) nbfe++;
+				if ( nbswp < 0 && k < 5){
+					_error_("Missing Edge " << i << ", v0=" << GetId(edges[i][0]) << ",v1=" << GetId(edges[i][1]));
+				}
+			}
+
+			if (k!=0) {
+				_error_("There are " << k << " lost edges, the boundary might be crossing");
+			}
+			for (int j=0;j<nbv;j++){
+				Nbswap +=  vertices[j].Optim(1,0);
+			}
+			if (verbose > 3) _printf_("      number of inforced edge = " << nbfe << ", number of swap= " << Nbswap << "\n"); 
+		}
+	/*}}}*/
+	/*FUNCTION Mesh::FindSubDomain{{{*/
+	void Mesh::FindSubDomain(int OutSide) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindSubDomain)*/
+
+		long int verbose=0;
+
+		if (verbose >2){
+			if (OutSide) _printf_("   Find all external sub-domain\n"); 
+			else _printf_("   Find all internal sub-domain\n");
+		  }
+		short * HeapArete = new short[nbt];
+		Triangle  **  HeapTriangle = new Triangle*  [nbt];
+		Triangle *t,*t1;
+		long k,it;
+
+		for (int itt=0;itt<nbt;itt++) 
+		 triangles[itt].link=0; // par defaut pas de couleur
+
+		long  NbSubDomTot =0;
+		for ( it=0;it<nbt;it++)  { 
+			if ( ! triangles[it].link  ) {
+				t = triangles + it;
+				NbSubDomTot++;; // new composante connexe
+				long i = 0; // niveau de la pile 
+				t->link = t ; // sd forme d'un triangle cicular link
+
+				HeapTriangle[i] =t ; 
+				HeapArete[i] = 3;
+
+				while (i >= 0) // boucle sur la pile
+				  { while ( HeapArete[i]--) // boucle sur les 3 aretes 
+					  { 
+						int na =  HeapArete[i];
+						Triangle * tc =  HeapTriangle[i]; // triangle courant
+						if( ! tc->Locked(na)) // arete non frontiere
+						  {
+							Triangle * ta = tc->TriangleAdj(na) ; // næ triangle adjacent
+							if (ta->link == 0 ) // non deja chainer => on enpile
+							  { 
+								i++;
+								ta->link = t->link ;  // on chaine les triangles
+								t->link = ta ;  // d'un meme sous domaine          
+								HeapArete[i] = 3; // pour les 3 triangles adjacents
+								HeapTriangle[i] = ta;
+							  }}
+					  } // deplie fin de boucle sur les 3 adjacences
+					i--;
+				  }          
+			}      
+		}
+
+		// supression de tous les sous domaine infini <=>  contient le sommet NULL
+		it =0;
+		nbtout = 0;
+		while (it<nbt) {
+			if (triangles[it].link) 
+			  { 
+				if (!( triangles[it](0) &&  triangles[it](1) &&  triangles[it](2) )) 
+				  {
+					// infini triangle 
+					NbSubDomTot --;
+					t=&triangles[it];
+					nbtout--;  // on fait un coup de trop. 
+					while  (t){
+						nbtout++;
+						t1=t;
+						t=t->link;
+						t1->link=0;
+					}
+				  }
+			  }   
+			it++;} // end while (it<nbt)
+			if (nbt == nbtout ||  !NbSubDomTot) {
+				delete [] HeapArete;
+				_error_("The boundary is not close: all triangles are outside");
+			}
+
+			delete [] HeapArete;
+			delete [] HeapTriangle;
+
+			if (OutSide|| !Gh.subdomains || !Gh.nbsubdomains ) 
+			  { // No geom sub domain
+				long i;
+				if (subdomains) delete [] subdomains;
+				subdomains = new SubDomain[ NbSubDomTot];
+				nbsubdomains=  NbSubDomTot;
+				for ( i=0;i<nbsubdomains;i++) {
+					subdomains[i].head=NULL;
+					subdomains[i].ReferenceNumber=i+1;
+				}
+				long * mark = new long[nbt];
+				for (it=0;it<nbt;it++)
+				 mark[it]=triangles[it].link ? -1 : -2;
+
+				it =0;
+				k = 0;
+				while (it<nbt) {
+					if (mark[it] == -1) {
+						t1 = & triangles[it];
+						t = t1->link;
+						mark[it]=k;
+						subdomains[k].head = t1;
+						do {
+							mark[GetId(t)]=k;
+							t=t->link;
+						} while (t!=t1);
+						mark[it]=k++;}
+						//    else if(mark[it] == -2 ) triangles[it].Draw(999);
+						it++;} // end white (it<nbt)
+						if (k!=nbsubdomains){
+							delete [] mark;
+							_error_("k!=nbsubdomains");
+						}
+						if(OutSide) 
+						  {
+							//  to remove all the sub domain by parity adjacents
+							//  because in this case we have only the true boundary edge
+							// so teh boundary is manifold
+							long nbk = nbsubdomains;
+							while (nbk)
+							 for (it=0;it<nbt && nbk ;it++)
+							  for (int na=0;na<3 && nbk ;na++)
+								 {
+								  Triangle *ta = triangles[it].TriangleAdj(na);
+								  long kl = ta ? mark[GetId(ta)] : -2;
+								  long kr = mark[it];
+								  if(kr !=kl) {
+									  if (kl >=0 && subdomains[kl].ReferenceNumber <0 && kr >=0 && subdomains[kr].ReferenceNumber>=0)
+										nbk--,subdomains[kr].ReferenceNumber=subdomains[kl].ReferenceNumber-1;
+									  if (kr >=0 && subdomains[kr].ReferenceNumber <0 && kl >=0 && subdomains[kl].ReferenceNumber>=0)
+										nbk--,subdomains[kl].ReferenceNumber=subdomains[kr].ReferenceNumber-1;
+									  if(kr<0 && kl >=0 && subdomains[kl].ReferenceNumber>=0)
+										nbk--,subdomains[kl].ReferenceNumber=-1;
+									  if(kl<0 && kr >=0 && subdomains[kr].ReferenceNumber>=0)
+										nbk--,subdomains[kr].ReferenceNumber=-1;
+								  }
+								 }
+							long  j=0;
+							for ( i=0;i<nbsubdomains;i++)
+							 if((-subdomains[i].ReferenceNumber) %2) { // good 
+								 if(i != j) 
+								  Exchange(subdomains[i],subdomains[j]);
+								 j++;}
+							 else{ 
+								 t= subdomains[i].head;
+								 while (t){
+									 nbtout++;
+									 t1=t;
+									 t=t->link;
+									 t1->link=0;
+								 }//while (t)
+								}
+							if(verbose>4) _printf_("      Number of removes subdomains (OutSideMesh) = " << nbsubdomains-j << "\n");
+							nbsubdomains=j;
+						  }
+
+						delete []  mark; 
+
+			  }
+			else
+			  { // find the head for all sub domaine
+				if (Gh.nbsubdomains != nbsubdomains && subdomains)
+				 delete [] subdomains, subdomains=0;
+				if (! subdomains  ) 
+				 subdomains = new SubDomain[ Gh.nbsubdomains];
+				nbsubdomains =Gh.nbsubdomains;
+				long err=0;
+				CreateSingleVertexToTriangleConnectivity();
+				long * mark = new long[nbt];
+				Edge **GeomEdgetoEdge = MakeGeomEdgeToEdge();
+
+				for (it=0;it<nbt;it++)
+				 mark[it]=triangles[it].link ? -1 : -2;
+				long inew =0;
+				for (int i=0;i<nbsubdomains;i++) {
+					GeomEdge &eg = *Gh.subdomains[i].edge;
+					subdomains[i].ReferenceNumber = Gh.subdomains[i].ReferenceNumber;
+					int ssdlab = subdomains[i].ReferenceNumber;
+					// by carefull is not easy to find a edge create from a GeomEdge 
+					// see routine MakeGeomEdgeToEdge
+					Edge &e = *GeomEdgetoEdge[Gh.GetId(eg)];
+					_assert_(&e);
+					BamgVertex * v0 =  e(0),*v1 = e(1);
+					Triangle *t  = v0->t;
+					int direction = Gh.subdomains[i].direction;
+					// test if ge and e is in the same direction 
+					if (((eg[0].r-eg[1].r),(e[0].r-e[1].r))<0) direction = -direction ;
+					subdomains[i].direction = direction;
+					subdomains[i].edge = &e;
+					_assert_(t && direction);
+
+					AdjacentTriangle  ta(t,EdgesVertexTriangle[v0->IndexInTriangle][0]);// previous edges
+
+					while (1) {
+						_assert_(v0==ta.EdgeVertex(1));
+						if (ta.EdgeVertex(0) == v1) { // ok we find the edge
+							if (direction>0)  
+							 subdomains[i].head=t=Adj(ta);
+							else 
+							 subdomains[i].head=t=ta;
+							if(t<triangles || t >= triangles+nbt || t->det < 0 || t->link == 0) {
+								_error_("bad definition of SubSomain " << i);
+							}
+							long it = GetId(t);
+							if (mark[it] >=0) {
+								break;
+							}
+							if(i != inew) 
+							 Exchange(subdomains[i],subdomains[inew]);
+							inew++;
+							Triangle *tt=t;
+							long kkk=0;
+							do 
+							  {
+								kkk++;
+								if (mark[GetId(tt)]>=0){
+									_error_("mark[GetId(tt)]>=0");
+								}
+								mark[GetId(tt)]=i;
+								tt=tt->link;
+							  } while (tt!=t);
+							break;
+						}
+						ta = Previous(Adj(ta));         
+						if(t == (Triangle *) ta) {
+							_error_("bad definition of SubSomain " << i);
+						}
+					}
+				}
+
+				if (inew < nbsubdomains) {
+					if (verbose>5) _printf_("WARNING: " << nbsubdomains-inew << " SubDomains are being removed\n");
+					nbsubdomains=inew;}
+
+					for (it=0;it<nbt;it++)
+					 if ( mark[it] ==-1 ) 
+					  nbtout++,triangles[it].link =0;
+					delete [] GeomEdgetoEdge;
+					delete [] mark;
+
+			  }
+			nbtout=0;
+			for (it=0;it<nbt;it++) 
+			 if(!triangles[it].link)  nbtout++;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::GetId(const Triangle & t) const{{{*/
+	long Mesh::GetId(const Triangle & t) const  { 
+		return &t - triangles;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::GetId(const Triangle * t) const{{{*/
+	long Mesh::GetId(const Triangle * t) const  { 
+		return t - triangles;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::GetId(const BamgVertex & t) const{{{*/
+	long Mesh::GetId(const BamgVertex & t) const  { 
+		return &t - vertices;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::GetId(const BamgVertex * t) const{{{*/
+	long Mesh::GetId(const BamgVertex * t) const  { 
+		return t - vertices;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::GetId(const Edge & t) const{{{*/
+	long Mesh::GetId(const Edge & t) const  { 
+		return &t - edges;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::GetId(const Edge * t) const{{{*/
+	long Mesh::GetId(const Edge * t) const  { 
+		return t - edges;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::Init{{{*/
+	void Mesh::Init(long maxnbv_in) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/PreInit)*/
+
+		/* initialize random seed: */
+		srand(19999999);
+
+		/*Initialize fields*/
+		NbRef=0;
+		quadtree=NULL;
+		nbv=0;
+		nbt=0;
+		nbe=0;
+		edges=NULL;
+		nbq=0;
+		nbsubdomains=0;
+		subdomains=NULL;
+		maxnbv=maxnbv_in;
+		maxnbt=2 *maxnbv_in-2;
+		NbVertexOnBThVertex=0;
+		VertexOnBThVertex=NULL;
+		NbVertexOnBThEdge=0;
+		VertexOnBThEdge=NULL;
+		NbCrackedVertices=0;
+		CrackedVertices =NULL;
+		NbCrackedEdges =0;
+		CrackedEdges =NULL;
+		NbVerticesOnGeomVertex=0;
+		VerticesOnGeomVertex=NULL;
+		NbVerticesOnGeomEdge=0;
+		VerticesOnGeomEdge=NULL;
+
+		/*Allocate if maxnbv_in>0*/
+		if (maxnbv_in) {
+			vertices=new BamgVertex[maxnbv];
+			_assert_(vertices);
+			orderedvertices=new (BamgVertex* [maxnbv]);
+			_assert_(orderedvertices);
+			triangles=new Triangle[maxnbt];
+			_assert_(triangles);
+		}
+		else {
+			vertices=NULL;
+			orderedvertices=NULL;
+			triangles=NULL;
+			maxnbt=0;
+		} 
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::Insert{{{*/
+	void Mesh::Insert() {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Insert)*/
+
+		/*Insert points in the existing Geometry*/
+
+		//Intermediary
+		int i;
+
+		/*Get options*/
+		long int verbose=2;
+
+		//Display info
+		if (verbose>2) _printf_("   Insert initial " << nbv << " vertices\n");
+
+		//Compute integer coordinates for the existing vertices
+		SetIntCoor();
+
+		/*Now we want to build a list (orderedvertices) of the vertices in a random
+		 * order. To do so, we use the following method:
+		 *
+		 * From an initial k0 in [0 nbv[ random (vertex number)
+		 * the next k (vertex number) is computed using a big
+		 * prime number (PN>>nbv) following:
+		 *
+		 * k_{i+1} = k_i + PN  [nbv]
+		 *
+		 * let's show that:
+		 *
+		 *   for all j in [0 nbv[, ∃! i in [0 nbv[ such that k_i=j
+		 *
+		 * Let's assume that there are 2 distinct j1 and j2 such that
+		 * k_j1 = k_j2
+		 *
+		 * This means that
+		 *  
+		 *  k0+j1*PN = k0+j2*PN [nbv]
+		 *  (j1-j2)*PN =0       [nbv]
+		 * since PN is a prime number larger than nbv, and nbv!=1
+		 *  j1-j2=0             [nbv]
+		 * BUT
+		 *  j1 and j2 are in [0 nbv[ which is impossible.
+		 *
+		 *  We hence have built a random list of nbv elements of
+		 *  [0 nbv[ all distincts*/
+
+		//Get Prime number
+		const long PrimeNumber= BigPrimeNumber(nbv);
+		int   k0=rand()%nbv; 
+
+		//Build orderedvertices
+		for (i=0; i<nbv; i++){
+			orderedvertices[i]=&vertices[k0=(k0+PrimeNumber)%nbv];
+		}
+
+		/*Modify orderedvertices such that the first 3 vertices form a triangle*/
+
+		//get first vertex i such that [0,1,i] are not aligned
+		for (i=2; det(orderedvertices[0]->i,orderedvertices[1]->i,orderedvertices[i]->i)==0;){
+			//if i is higher than nbv, it means that all the determinants are 0,
+			//all vertices are aligned!
+			if  (++i>=nbv) _error_("all the vertices are aligned");
+		}
+		// exchange i et 2 in "orderedvertices" so that
+		// the first 3 vertices are not aligned (real triangle)
+		Exchange(orderedvertices[2], orderedvertices[i]);
+
+		/*Take the first edge formed by the first two vertices and build
+		 * the initial simple mesh from this edge and 2 boundary triangles*/
+
+		BamgVertex *v0=orderedvertices[0], *v1=orderedvertices[1];
+
+		nbt = 2;
+		triangles[0](0) = NULL;//infinite vertex
+		triangles[0](1) = v0;
+		triangles[0](2) = v1;
+		triangles[1](0) = NULL;//infinite vertex
+		triangles[1](2) = v0;
+		triangles[1](1) = v1;
+
+		//Build adjacence
+		const int e0 = OppositeEdge[0];
+		const int e1 = NextEdge[e0];
+		const int e2 = PreviousEdge[e0];
+		triangles[0].SetAdj2(e0, &triangles[1] ,e0);
+		triangles[0].SetAdj2(e1, &triangles[1] ,e2);
+		triangles[0].SetAdj2(e2, &triangles[1] ,e1);
+
+		triangles[0].det = -1;  //boundary triangle: det = -1
+		triangles[1].det = -1;  //boundary triangle: det = -1
+
+		triangles[0].SetSingleVertexToTriangleConnectivity();
+		triangles[1].SetSingleVertexToTriangleConnectivity();
+
+		triangles[0].link=&triangles[1];
+		triangles[1].link=&triangles[0];
+
+		//build quadtree
+		if (!quadtree)  quadtree = new BamgQuadtree(this,0);
+		quadtree->Add(*v0);
+		quadtree->Add(*v1);
+
+		/*Now, add the vertices One by One*/
+		long NbSwap=0;
+		if (verbose>3) _printf_("   Begining of insertion process...\n");
+
+		for (int icount=2; icount<nbv; icount++) {
+
+			//Get new vertex
+			BamgVertex *newvertex=orderedvertices[icount];
+
+			//Find the triangle in which newvertex is located
+			Icoor2 det3[3];
+			Triangle* tcvi = TriangleFindFromCoord(newvertex->i,det3); //(newvertex->i = integer coordinates)
+
+			//Add newvertex to the quadtree
+			quadtree->Add(*newvertex); 
+
+			//Add newvertex to the existing mesh
+			AddVertex(*newvertex,tcvi,det3);
+
+			//Make the mesh Delaunay around newvertex by swaping the edges
+			NbSwap += newvertex->Optim(1,0);
+		}
+
+		//Display info
+		if (verbose>3) {
+			_printf_("      NbSwap of insertion: " << NbSwap << "\n");
+			_printf_("      NbSwap/nbv:          " << NbSwap/nbv << "\n");
+		}
+
+#ifdef NBLOOPOPTIM
+
+		k0 = rand()%nbv ; 
+		for (int is4=0; is4<nbv; is4++) 
+		 orderedvertices[is4]= &vertices[k0 = (k0 + PrimeNumber)% nbv];
+
+		for(int Nbloop=0;Nbloop<NBLOOPOPTIM;Nbloop++){
+			long  NbSwap = 0;
+			for (int is1=0; is1<nbv; is1++) 
+			 NbSwap += orderedvertices[is1]->Optim(0,0);
+			if (verbose>3) {
+				_printf_("      Optim Loop: " << Nbloop << "\n");
+				_printf_("      NbSwap/nbv:          " << NbSwap/nbv << "\n");
+			}
+			if(!NbSwap) break;
+		}
+		CreateSingleVertexToTriangleConnectivity(); 
+		// because we break the TriangleContainingTheVertex
+#endif
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::InsertNewPoints{{{*/
+	long Mesh::InsertNewPoints(long nbvold,long & NbTSwap) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/InsertNewPoints)*/
+
+		long int verbose=0;
+		double seuil= 1.414/2 ;// for two close point 
+		long i;
+		long NbSwap=0;
+		Icoor2 det3[3];
+
+		//number of new points
+		const long nbvnew=nbv-nbvold;
+
+		//display info if required
+		if (verbose>5) _printf_("      Try to Insert " << nbvnew << " new points\n");
+
+		//return if no new points
+		if (!nbvnew) return 0; 
+
+		/*construction of a random order*/
+		const long PrimeNumber= BigPrimeNumber(nbv)  ;
+		//remainder of the division of rand() by nbvnew
+		long k3 = rand()%nbvnew;
+		//loop over the new points
+		for (int is3=0; is3<nbvnew; is3++){
+			register long j=nbvold +(k3 = (k3+PrimeNumber)%nbvnew);
+			register long i=nbvold+is3; 
+			orderedvertices[i]= vertices + j;
+			orderedvertices[i]->ReferenceNumber=i;
+		}
+
+		// for all the new point
+		long iv=nbvold;
+		for (i=nbvold;i<nbv;i++){
+			BamgVertex &vi=*orderedvertices[i];
+			vi.i=R2ToI2(vi.r);
+			vi.r=I2ToR2(vi.i);
+			double hx,hy;
+			vi.m.Box(hx,hy);
+			Icoor1 hi=(Icoor1) (hx*coefIcoor),hj=(Icoor1) (hy*coefIcoor);
+			if (!quadtree->ToClose(vi,seuil,hi,hj)){
+				// a good new point 
+				BamgVertex &vj = vertices[iv];
+				long  j=vj.ReferenceNumber; 
+				if (&vj!=orderedvertices[j]){
+					_error_("&vj!= orderedvertices[j]");
+				}
+				if(i!=j){ 
+					Exchange(vi,vj);
+					Exchange(orderedvertices[j],orderedvertices[i]);
+				}
+				vj.ReferenceNumber=0; 
+				Triangle *tcvj=TriangleFindFromCoord(vj.i,det3);
+				if (tcvj && !tcvj->link){
+					tcvj->Echo();
+					_error_("problem inserting point in InsertNewPoints (tcvj=" << tcvj << " and tcvj->link=" << tcvj->link << ")");
+				}
+				quadtree->Add(vj);
+				AddVertex(vj,tcvj,det3);
+				NbSwap += vj.Optim(1);          
+				iv++;
+			}
+		} 
+		if (verbose>3) {
+			_printf_("         number of new points: " << iv << "\n");
+			_printf_("         number of to close (?) points: " << nbv-iv << "\n");
+			_printf_("         number of swap after: " << NbSwap << "\n");
+		}
+		nbv = iv;
+
+		for (i=nbvold;i<nbv;i++) NbSwap += vertices[i].Optim(1);  
+		if (verbose>3) _printf_("   NbSwap=" << NbSwap << "\n");
+
+		NbTSwap +=  NbSwap ;
+		return nbv-nbvold;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::isCracked{{{*/
+	int Mesh::isCracked() const {
+		return NbCrackedVertices != 0;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::MakeGeomEdgeToEdge{{{*/
+	Edge** Mesh::MakeGeomEdgeToEdge() {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeGeomEdgeToEdge)*/
+
+		if (!Gh.nbe){
+			_error_("!Gh.nbe");
+		}
+		Edge **e= new (Edge* [Gh.nbe]);
+
+		long i;
+		for ( i=0;i<Gh.nbe ; i++)
+		 e[i]=NULL;
+		for ( i=0;i<nbe ; i++) 
+		  { 
+			Edge * ei = edges+i;
+			GeomEdge *GeomEdgeHook = ei->GeomEdgeHook; 
+			e[Gh.GetId(GeomEdgeHook)] = ei;    
+		  }
+		for ( i=0;i<nbe ; i++) 
+		 for (int ii=0;ii<2;ii++) { 
+			 Edge * ei = edges+i;
+			 GeomEdge *GeomEdgeHook = ei->GeomEdgeHook;
+			 int j= ii;
+			 while (!(*GeomEdgeHook)[j].Required()) { 
+				 Adj(GeomEdgeHook,j); // next geom edge
+				 j=1-j;
+				 if (e[Gh.GetId(GeomEdgeHook)])  break; // optimisation
+				 e[Gh.GetId(GeomEdgeHook)] = ei; 
+			 }
+		 }
+
+		int kk=0;
+		for ( i=0;i<Gh.nbe ; i++){
+			if (!e[i]){
+				kk++;
+				if(kk<10) _printf_("BUG: the geometrical edge " << i << " is on no edge curve\n");
+			}
+		}
+		if(kk) _error_("See above");
+
+		return e;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::MakeQuadrangles{{{*/
+	void Mesh::MakeQuadrangles(double costheta){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeQuadrangles)*/
+
+		long int verbose=0;
+
+		if (verbose>2) _printf_("MakeQuadrangles costheta = " << costheta << "\n");
+
+		if (costheta >1) {
+			if (verbose>5) _printf_("   do nothing: costheta > 1\n");
+		}
+
+			long nbqq = (nbt*3)/2;
+			DoubleAndInt *qq = new DoubleAndInt[nbqq];
+
+			long i,ij;
+			int j;
+			long k=0;
+			for (i=0;i<nbt;i++)
+			 for (j=0;j<3;j++)
+			  if ((qq[k].q=triangles[i].QualityQuad(j))>=costheta)
+				qq[k++].i3j=i*3+j;
+			//  sort  qq
+			HeapSort(qq,k);
+
+			long kk=0;
+			for (ij=0;ij<k;ij++) { 
+				i=qq[ij].i3j/3;
+				j=(int) (qq[ij].i3j%3);
+				// optisamition no float computation  
+				if (triangles[i].QualityQuad(j,0) >=costheta) 
+				 triangles[i].SetHidden(j),kk++;
+			  }
+			nbq = kk;
+			if (verbose>2){
+				_printf_("   number of quadrilaterals    = " << nbq << "\n");
+				_printf_("   number of triangles         = " << nbt-nbtout- nbq*2 << "\n");
+				_printf_("   number of outside triangles = " << nbtout << "\n");
+			}
+			delete [] qq;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::MakeBamgQuadtree{{{*/
+	void Mesh::MakeBamgQuadtree() {  
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeBamgQuadtree)*/
+
+		long int verbose=0;
+		if (  !quadtree )  quadtree = new BamgQuadtree(this);
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::MaxinalHmax{{{*/
+	double Mesh::MaximalHmax() {
+		return Max(pmax.x-pmin.x,pmax.y-pmin.y);
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::MaxSubDivision{{{*/
+	void  Mesh::MaxSubDivision(double maxsubdiv) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/MaxSubDivision)*/
+
+		long int verbose=0;
+
+		const  double maxsubdiv2 = maxsubdiv*maxsubdiv;
+		if(verbose>1) _printf_("   Limit the subdivision of a edges in the new mesh by " << maxsubdiv << "\n");
+		// for all the edges 
+		// if the len of the edge is to long 
+		long it,nbchange=0;    
+		double lmax=0;
+		for (it=0;it<nbt;it++){
+			Triangle &t=triangles[it];
+			for (int j=0;j<3;j++){
+				Triangle &tt = *t.TriangleAdj(j);
+				if ( ! &tt ||  it < GetId(tt) && ( tt.link || t.link)){
+					BamgVertex &v0 = t[VerticesOfTriangularEdge[j][0]];
+					BamgVertex &v1 = t[VerticesOfTriangularEdge[j][1]];
+					R2 AB= (R2) v1-(R2) v0;
+					Metric M = v0;
+					double l = M(AB,AB);
+					lmax = Max(lmax,l);
+					if(l> maxsubdiv2){
+					  R2 AC = M.Orthogonal(AB);// the ortogonal vector of AB in M
+						double lc = M(AC,AC);
+						D2xD2 Rt(AB,AC);// Rt.x = AB , Rt.y = AC;
+						D2xD2 Rt1(Rt.inv());
+						D2xD2 D(maxsubdiv2,0,0,lc);
+						D2xD2 MM = Rt1*D*Rt1.t();
+						v0.m =  M = Metric(MM.x.x,MM.y.x,MM.y.y);
+						nbchange++;
+					}
+					M = v1;
+					l = M(AB,AB);
+					lmax = Max(lmax,l);
+					if(l> maxsubdiv2){
+					  R2 AC = M.Orthogonal(AB);// the ortogonal vector of AB in M
+						double lc = M(AC,AC);
+						D2xD2 Rt(AB,AC);// Rt.x = AB , Rt.y = AC;
+						D2xD2 Rt1(Rt.inv());
+						D2xD2 D(maxsubdiv2,0,0,lc);
+						D2xD2  MM = Rt1*D*Rt1.t();
+						v1.m =  M = Metric(MM.x.x,MM.y.x,MM.y.y);
+						nbchange++;
+					}
+				}
+			}
+		}
+		if(verbose>3){
+			_printf_("      number of metric changes = " << nbchange << ", maximum number of subdivision of a edges before change = " << pow(lmax,0.5) << "\n");
+		}
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::MetricAt{{{*/
+	Metric Mesh::MetricAt(const R2 & A) const { 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MetricAt)*/
+
+		I2 a = R2ToI2(A);
+		Icoor2 deta[3];
+		Triangle * t =TriangleFindFromCoord(a,deta);
+		if (t->det <0) { // outside
+			double ba,bb;
+			AdjacentTriangle edge= CloseBoundaryEdge(a,t,ba,bb) ;
+			return Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1));}
+		else { // inside
+			double   aa[3];
+			double s = deta[0]+deta[1]+deta[2];
+			aa[0]=deta[0]/s;
+			aa[1]=deta[1]/s;
+			aa[2]=deta[2]/s;
+			return Metric(aa,(*t)[0],(*t)[1],(*t)[2]);
+		}
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::MininalHmin{{{*/
+	double Mesh::MinimalHmin() {
+		return 2.0/coefIcoor;
+	}
+	/*}}}*/
+/*FUNCTION Mesh::NearestVertex{{{*/
+BamgVertex* Mesh::NearestVertex(Icoor1 i,Icoor1 j) {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NearestVertex)*/
+	return  quadtree->NearestVertex(i,j); 
+} 
+/*}}}*/
+	/*FUNCTION Mesh::NewPoints{{{*/
+	void  Mesh::NewPoints(Mesh & Bh,BamgOpts* bamgopts,int KeepVertices){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewPoints)*/
+
+		int i,j,k;
+		long NbTSwap=0;
+		long nbtold=nbt;
+		long nbvold=nbv;
+		long Headt=0;
+		long next_t;
+		long* first_np_or_next_t=new long[maxnbt];
+		Triangle* t=NULL;
+
+		/*Recover options*/
+		int verbose=bamgopts->verbose;
+
+		/*First, insert old points if requested*/
+		if (KeepVertices && (&Bh != this) && (nbv+Bh.nbv< maxnbv)){
+			if (verbose>5) _printf_("         Inserting initial mesh points\n");
+			for (i=0;i<Bh.nbv;i++){ 
+				BamgVertex &bv=Bh[i];
+				if (!bv.GeomEdgeHook){
+					vertices[nbv].r   = bv.r;
+					vertices[nbv++].m = bv.m;
+				}
+			}
+			Bh.CreateSingleVertexToTriangleConnectivity();     
+			InsertNewPoints(nbvold,NbTSwap)   ;            
+		}  
+		else Bh.CreateSingleVertexToTriangleConnectivity();     
+
+		// generation of the list of next Triangle 
+		for(i=0;i<nbt;i++) first_np_or_next_t[i]=-(i+1);
+		// the next traingle of i is -first_np_or_next_t[i]
+
+		// Big loop (most time consuming)
+		int iter=0;
+		if (verbose>5) _printf_("         Big loop\n");
+		do {
+			/*Update variables*/
+			iter++;
+			nbtold=nbt;
+			nbvold=nbv;
+
+			/*We test all triangles*/
+			i=Headt;
+			next_t=-first_np_or_next_t[i];
+			for(t=&triangles[i];i<nbt;t=&triangles[i=next_t],next_t=-first_np_or_next_t[i]){
+
+				//check i
+				if (i<0 || i>=nbt ){
+					_error_("Index problem in NewPoints (i=" << i << " not in [0 " << nbt-1 << "])");
+				}
+				//change first_np_or_next_t[i]
+				first_np_or_next_t[i] = iter; 
+
+				//Loop over the edges of t
+				for(j=0;j<3;j++){
+					AdjacentTriangle tj(t,j);
+					BamgVertex &vA = *tj.EdgeVertex(0);
+					BamgVertex &vB = *tj.EdgeVertex(1);
+
+					//if t is a boundary triangle, or tj locked, continue
+					if (!t->link)     continue;
+					if (t->det <0)    continue;
+					if (t->Locked(j)) continue;
+
+					AdjacentTriangle tadjj = t->Adj(j);	  
+					Triangle* ta=tadjj;
+
+					//if the adjacent triangle is a boundary triangle, continur
+					if (ta->det<0) continue;	  
+
+					R2 A=vA;
+					R2 B=vB;
+					k=GetId(ta);
+
+					//if this edge has already been done, go to next edge of triangle
+					if(first_np_or_next_t[k]==iter) continue;
+
+					lIntTria.SplitEdge(Bh,A,B);
+					lIntTria.NewPoints(vertices,nbv,maxnbv);
+				  } // end loop for each edge 
+			  }// for triangle   
+
+			if (!InsertNewPoints(nbvold,NbTSwap)) break;
+			for (i=nbtold;i<nbt;i++) first_np_or_next_t[i]=iter;
+			Headt = nbt; // empty list 
+
+			// for all the triangle containing the vertex i
+			for (i=nbvold;i<nbv;i++){ 
+				BamgVertex*          s  = vertices + i;
+				AdjacentTriangle ta(s->t, EdgesVertexTriangle[s->IndexInTriangle][1]);
+				Triangle*        tbegin= (Triangle*) ta;
+				long kt;
+				do { 
+					kt = GetId((Triangle*) ta);
+					if (first_np_or_next_t[kt]>0){
+						first_np_or_next_t[kt]=-Headt;
+						Headt=kt;
+					}
+					if (ta.EdgeVertex(0)!=s){
+						_error_("ta.EdgeVertex(0)!=s");
+					}
+					ta = Next(Adj(ta));
+				} while ( (tbegin != (Triangle*) ta)); 
+			}
+
+		} while (nbv!=nbvold);
+
+		delete []  first_np_or_next_t;
+
+		long NbSwapf =0,NbSwp;
+
+		NbSwp = NbSwapf;
+		for (i=0;i<nbv;i++)
+		 NbSwapf += vertices[i].Optim(0);
+		NbTSwap +=  NbSwapf ;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::ProjectOnCurve{{{*/
+	GeomEdge*   Mesh::ProjectOnCurve( Edge & BhAB, BamgVertex &  vA, BamgVertex & vB,
+				double theta,BamgVertex & R,VertexOnEdge &  BR,VertexOnGeom & GR) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/ProjectOnCurve)*/
+
+		void *pA=0,*pB=0;
+		double tA=0,tB=0;
+		R2 A=vA,B=vB;
+		BamgVertex * pvA=&vA, * pvB=&vB;
+		if (vA.IndexInTriangle == IsVertexOnVertex){
+			pA=vA.BackgroundVertexHook;
+		}
+		else if (vA.IndexInTriangle == IsVertexOnEdge){
+			pA=vA.BackgroundEdgeHook->be;
+			tA=vA.BackgroundEdgeHook->abcisse;
+		}
+		else {
+			_error_("ProjectOnCurve On BamgVertex " << BTh.GetId(vA) << " forget call to SetVertexFieldOnBTh");
+		} 
+
+		if (vB.IndexInTriangle == IsVertexOnVertex){
+			pB=vB.BackgroundVertexHook;
+		}
+		else if(vB.IndexInTriangle == IsVertexOnEdge){
+			pB=vB.BackgroundEdgeHook->be;
+			tB=vB.BackgroundEdgeHook->abcisse;
+		}
+		else {
+			_error_("ProjectOnCurve On BamgVertex " << BTh.GetId(vB) << " forget call to SetVertexFieldOnBTh");
+		} 
+		Edge * e = &BhAB;
+		if (!pA || !pB || !e){
+			_error_("!pA || !pB || !e");
+		}
+		// be carefull the back ground edge e is on same geom edge 
+		// of the initiale edge def by the 2 vertex A B;
+		//check Is a background Mesh;   
+		if (e<BTh.edges || e>=BTh.edges+BTh.nbe){
+			_error_("e<BTh.edges || e>=BTh.edges+BTh.nbe");
+		}
+		// walk on BTh edge 
+		//not finish ProjectOnCurve with BackGround Mesh);
+		// 1 first find a back ground edge contening the vertex A
+		// 2 walk n back gound boundary to find the final vertex B
+
+		if( vA.IndexInTriangle == IsVertexOnEdge) 
+		  { // find the start edge 
+			e = vA.BackgroundEdgeHook->be;	 
+
+		  } 
+		else if (vB.IndexInTriangle == IsVertexOnEdge) 
+		  {
+			theta = 1-theta;
+			Exchange(tA,tB);
+			Exchange(pA,pB);
+			Exchange(pvA,pvB);
+			Exchange(A,B);
+			e =  vB.BackgroundEdgeHook->be;
+
+		  } 
+		else{ // do the search by walking 
+			_error_("case not supported yet");
+		  }
+
+		// find the direction of walking with direction of edge and pA,PB;
+		R2 AB=B-A;
+
+		double cosE01AB = (( (R2) (*e)[1] - (R2) (*e)[0] ) , AB);
+		int kkk=0;
+		int direction = (cosE01AB>0) ? 1 : 0;
+
+		//   double l=0; // length of the edge AB
+		double abscisse = -1;
+
+		for (int step=0;step<2;step++){
+			// 2 times algo:
+			//    1 for computing the length l
+			//    2 for find the vertex 
+			int  iii;
+			BamgVertex  *v0=pvA,*v1; 
+			Edge *neee,*eee;
+			double lg =0; // length of the curve 
+			double te0;
+			// we suppose take the curve's abcisse 
+			for ( eee=e,iii=direction,te0=tA;
+						eee && ((( void*) eee) != pB) && (( void*) (v1=&((*eee)[iii]))) != pB ;
+						neee = eee->adj[iii],iii = 1-neee->Intersection(*eee),eee = neee,v0=v1,te0=1-iii ) { 
+
+				kkk=kkk+1;
+				_assert_(kkk<100);
+				_assert_(eee);
+				double lg0 = lg;
+				double dp = LengthInterpole(v0->m,v1->m,(R2) *v1 - (R2) *v0);
+				lg += dp;
+				if (step && abscisse <= lg) { // ok we find the geom edge 
+					double sss  =   (abscisse-lg0)/dp;
+					double thetab = te0*(1-sss)+ sss*iii;
+					_assert_(thetab>=0 && thetab<=1);
+					BR = VertexOnEdge(&R,eee,thetab);
+					return  Gh.ProjectOnCurve(*eee,thetab,R,GR);
+				  }
+			  }
+			// we find the end 
+			if (v1 != pvB){
+				if (( void*) v1 == pB)
+				 tB = iii;
+
+				double lg0 = lg;
+				_assert_(eee);
+				v1 = pvB;
+				double dp = LengthInterpole(v0->m,v1->m,(R2) *v1 - (R2) *v0);
+				lg += dp;	
+				abscisse = lg*theta;
+				if (abscisse <= lg && abscisse >= lg0 ) // small optimisation we know the lenght because end
+				  { // ok we find the geom edge 
+					double sss  =   (abscisse-lg0)/dp;
+					double thetab = te0*(1-sss)+ sss*tB;
+					_assert_(thetab>=0 && thetab<=1);
+					BR = VertexOnEdge(&R,eee,thetab);
+					return  Gh.ProjectOnCurve(*eee,thetab,R,GR);
+				  }
+			  }
+			abscisse = lg*theta;
+
+		  }
+		_error_("Big bug...");
+		return 0; // just for the compiler 
+	}                  
+	/*}}}*/
+/*FUNCTION Mesh::ReconstructExistingMesh{{{*/
+void Mesh::ReconstructExistingMesh(){
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FillHoleInMesh)*/
+
+	/*This routine reconstruct an existing mesh to make it CONVEX:
+	 * -all the holes are filled
+	 * -concave boundaries are filled
+	 * A convex mesh is required for a lot of operations. This is why every mesh
+	 * goes through this process.
+	 * This routine also generates mesh properties such as adjencies,...
+	 */
+
+	/*Intermediary*/
+	int verbose=0;
+
+	// generation of the integer coordinate
+
+	// find extrema coordinates of vertices pmin,pmax
+	long i;
+	if(verbose>2) _printf_("      Reconstruct mesh of " << nbv << " vertices\n"); 
+
+	//initialize orderedvertices
+	_assert_(orderedvertices);
+	for (i=0;i<nbv;i++) orderedvertices[i]=0;
+
+	//Initialize nbsubdomains
+	nbsubdomains =0;
+
+	/* generation of triangles adjacency*/
+
+	//First add existing edges
+	long kk =0;
+	SetOfEdges4* edge4= new SetOfEdges4(nbt*3,nbv);
+	for (i=0;i<nbe;i++){
+		kk=kk+(i==edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1])));
+	}
+	if (kk != nbe){ 
+		_error_("There are " << kk-nbe << " double edges in the mesh");
+	}
+
+	//Add edges of all triangles in existing mesh
+	long* st = new long[nbt*3];
+	for (i=0;i<nbt*3;i++) st[i]=-1;
+	for (i=0;i<nbt;i++){
+		for (int j=0;j<3;j++){
+
+			//Add current triangle edge to edge4
+			long k =edge4->SortAndAdd(GetId(triangles[i][VerticesOfTriangularEdge[j][0]]),GetId(triangles[i][VerticesOfTriangularEdge[j][1]]));
+
+			long invisible=triangles[i].Hidden(j);
+
+			//If the edge has not been added to st, add it
+			if(st[k]==-1) st[k]=3*i+j;
+
+			//If the edge already exists, add adjacency
+			else if(st[k]>=0) {
+				_assert_(!triangles[i].TriangleAdj(j));
+				_assert_(!triangles[st[k]/3].TriangleAdj((int) (st[k]%3)));
+
+				triangles[i].SetAdj2(j,triangles+st[k]/3,(int)(st[k]%3));
+				if (invisible) triangles[i].SetHidden(j);
+				if (k<nbe)     triangles[i].SetLocked(j);
+
+				//Make st[k] negative so that it will throw an error message if it is found again
+				st[k]=-2-st[k]; 
+			}
+
+			//An edge belongs to 2 triangles
+			else {
+				_error_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << " , " << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles");
+			}
+		}
+	}
+
+	//Display info if required
+	if(verbose>5) {
+		_printf_("         info of Mesh:\n");
+		_printf_("            - number of vertices    = " << nbv << " \n"); 
+		_printf_("            - number of triangles   = " << nbt << " \n"); 
+		_printf_("            - number of given edges = " << nbe << " \n"); 
+		_printf_("            - number of all edges   = " << edge4->nb() << "\n"); 
+		_printf_("            - Euler number 1 - nb of holes = " << nbt-edge4->nb()+nbv << "\n"); 
+	}
+
+	//check the consistency of edge[].adj and the geometrical required vertex
+	long k=0;
+	for (i=0;i<edge4->nb();i++){
+		if (st[i]>=0){ // edge alone 
+			if (i<nbe){
+				long i0=edge4->i(i);
+				orderedvertices[i0] = vertices+i0;
+				long i1=edge4->j(i);
+				orderedvertices[i1] = vertices+i1;
+			}
+			else {
+				k=k+1;
+				if (k<10) {
+					//print only 10 edges
+					_printf_("Lost boundary edges " << i << " : " << edge4->i(i) << " " << edge4->j(i) << "\n");
+				}
+				else if (k==10){
+					_printf_("Other lost boundary edges not shown...\n");
+				}
+			}
+		}
+	}
+	if(k) {
+		_error_(k << " boundary edges (from the geometry) are not defined as mesh edges");
+	}
+
+	/* mesh generation with boundary points*/
+	long nbvb=0;
+	for (i=0;i<nbv;i++){ 
+		vertices[i].t=0;
+		vertices[i].IndexInTriangle=0;
+		if (orderedvertices[i]) orderedvertices[nbvb++]=orderedvertices[i];
+	}
+
+	Triangle* savetriangles=triangles;
+	long savenbt=nbt;
+	long savemaxnbt=maxnbt;
+	SubDomain* savesubdomains=subdomains;
+	subdomains=0;
+
+	long  Nbtriafillhole=2*nbvb;
+	Triangle* triafillhole=new Triangle[Nbtriafillhole];
+	triangles = triafillhole;
+
+	nbt=2;
+	maxnbt= Nbtriafillhole;
+
+	//Find a vertex that is not aligned with vertices 0 and 1
+	for (i=2;det(orderedvertices[0]->i,orderedvertices[1]->i,orderedvertices[i]->i)==0;) 
+	 if  (++i>=nbvb) {
+		 _error_("ReconstructExistingMesh: All the vertices are aligned");
+	 }
+	//Move this vertex (i) to the 2d position in orderedvertices
+	Exchange(orderedvertices[2], orderedvertices[i]);
+
+	/*Reconstruct mesh beginning with 2 triangles*/
+	BamgVertex *  v0=orderedvertices[0], *v1=orderedvertices[1];
+
+	triangles[0](0) = NULL; // Infinite vertex
+	triangles[0](1) = v0;
+	triangles[0](2) = v1;
+
+	triangles[1](0) = NULL;// Infinite vertex
+	triangles[1](2) = v0;
+	triangles[1](1) = v1;
+	const int e0 = OppositeEdge[0];
+	const int e1 = NextEdge[e0];
+	const int e2 = PreviousEdge[e0];
+	triangles[0].SetAdj2(e0, &triangles[1] ,e0);
+	triangles[0].SetAdj2(e1, &triangles[1] ,e2);
+	triangles[0].SetAdj2(e2, &triangles[1] ,e1);
+
+	triangles[0].det = -1;  // boundary triangles
+	triangles[1].det = -1;  // boundary triangles
+
+	triangles[0].SetSingleVertexToTriangleConnectivity();
+	triangles[1].SetSingleVertexToTriangleConnectivity();
+
+	triangles[0].link=&triangles[1];
+	triangles[1].link=&triangles[0];
+
+	if (!quadtree) delete quadtree; //ReInitialise;
+	quadtree = new BamgQuadtree(this,0);
+	quadtree->Add(*v0);
+	quadtree->Add(*v1);
+
+	// vertices are added one by one
+	long NbSwap=0;
+	for (int icount=2; icount<nbvb; icount++) {
+		BamgVertex *vi  = orderedvertices[icount];
+		Icoor2 det3[3];
+		Triangle *tcvi = TriangleFindFromCoord(vi->i,det3);
+		quadtree->Add(*vi); 
+		AddVertex(*vi,tcvi,det3);
+		NbSwap += vi->Optim(1,1);
+	}
+
+	//enforce the boundary 
+	AdjacentTriangle ta(0,0);
+	long nbloss = 0,knbe=0;
+	for ( i = 0; i < nbe; i++){
+		if (st[i] >=0){ //edge alone => on border
+			BamgVertex &a=edges[i][0], &b=edges[i][1];
+			if (a.t && b.t){
+				knbe++;
+				if (ForceEdge(a,b,ta)<0) nbloss++;
+			}
+		}
+	}
+	if(nbloss) {
+		_error_("we lost " << nbloss << " existing edges other " << knbe);
+	}
+
+	FindSubDomain(1);
+	// remove all the hole 
+	// remove all the good sub domain
+	long krm =0;
+	for (i=0;i<nbt;i++){
+		if (triangles[i].link){ // remove triangles
+			krm++;
+			for (int j=0;j<3;j++){
+				AdjacentTriangle ta =  triangles[i].Adj(j);
+				Triangle &tta = *(Triangle*)ta;
+				//if edge between remove and not remove 
+				if(! tta.link){ 
+					// change the link of ta;
+					int ja = ta;
+					BamgVertex *v0= ta.EdgeVertex(0);
+					BamgVertex *v1= ta.EdgeVertex(1);
+					long k =edge4->SortAndAdd(v0?GetId(v0):nbv,v1? GetId(v1):nbv);
+
+					_assert_(st[k]>=0);
+					tta.SetAdj2(ja,savetriangles + st[k] / 3,(int) (st[k]%3));
+					ta.SetLock();
+					st[k]=-2-st[k]; 
+				}
+			}
+		}
+	}
+	long NbTfillHoll =0;
+	for (i=0;i<nbt;i++){
+		if (triangles[i].link) {
+			triangles[i]=Triangle((BamgVertex *) NULL,(BamgVertex *) NULL,(BamgVertex *) NULL);
+			triangles[i].color=-1;
+		}
+		else{
+			triangles[i].color= savenbt+ NbTfillHoll++;
+		}
+	}
+	_assert_(savenbt+NbTfillHoll<=savemaxnbt);
+
+	// copy of the outside triangles in saveMesh 
+	for (i=0;i<nbt;i++){
+		if(triangles[i].color>=0) {
+			savetriangles[savenbt]=triangles[i];
+			savetriangles[savenbt].link=0;
+			savenbt++;
+		}
+	}
+	// gestion of the adj
+	k =0;
+	Triangle * tmax = triangles + nbt;
+	for (i=0;i<savenbt;i++) { 
+		Triangle & ti = savetriangles[i];
+		for (int j=0;j<3;j++){
+			Triangle * ta = ti.TriangleAdj(j);
+			int aa = ti.NuEdgeTriangleAdj(j);
+			int lck = ti.Locked(j);
+			if (!ta) k++; // bug 
+			else if ( ta >= triangles && ta < tmax){
+				ta= savetriangles + ta->color;
+				ti.SetAdj2(j,ta,aa);
+				if(lck) ti.SetLocked(j);
+			}
+		}
+	}
+
+	// restore triangles;
+	nbt=savenbt;
+	maxnbt=savemaxnbt;
+	delete [] triangles;
+	delete [] subdomains;
+	triangles = savetriangles;
+	subdomains = savesubdomains;
+	if (k) {
+		_error_("number of triangles edges alone = " << k);
+	}
+	FindSubDomain();
+
+	delete edge4;
+	delete [] st;
+	for (i=0;i<nbv;i++) quadtree->Add(vertices[i]);
+
+	SetVertexFieldOn();
+
+	/*Check requirements consistency*/
+	for (i=0;i<nbe;i++){
+ 	/*If the current mesh edge is on Geometry*/
+		if(edges[i].GeomEdgeHook){
+			for(int j=0;j<2;j++){
+				/*Go through the edges adjacent to current edge (if on the same curve)*/
+				if (!edges[i].adj[j]){
+					/*The edge is on Geometry and does not have 2 adjacent edges... (not on a closed curve)*/
+					/*Check that the 2 vertices are on geometry AND required*/
+					if(!edges[i][j].GeomEdgeHook->IsRequiredVertex()){
+						_printf_("ReconstructExistingMesh error message: problem with the edge number " << i+1 << ": [" << GetId(edges[i][0])+1 << " " << GetId(edges[i][1])+1 << "]\n");
+						_printf_("This edge is on geometrical edge number " << Gh.GetId(edges[i].GeomEdgeHook)+1 << "\n");
+						if (edges[i][j].GeomEdgeHook->OnGeomVertex())
+						 _printf_("the vertex number " << GetId(edges[i][j])+1 << " of this edge is a geometric BamgVertex number " << Gh.GetId(edges[i][j].GeomEdgeHook->gv)+1 << "\n");
+						else if (edges[i][j].GeomEdgeHook->OnGeomEdge())
+						 _printf_("the vertex number " << GetId(edges[i][j])+1 << " of this edge is a geometric Edge number " << Gh.GetId(edges[i][j].GeomEdgeHook->ge)+1 << "\n");
+						else
+						 _printf_("Its pointer is " << edges[i][j].GeomEdgeHook << "\n");
+
+						_printf_("This edge is on geometry and has no adjacent edge (open curve) and one of the tip is not required\n");
+						_error_("See above (might be cryptic...)");
+					}
+				}
+			}
+		}
+	}
+}
+/*}}}*/
+	/*FUNCTION Mesh::TrianglesRenumberBySubDomain{{{*/
+	void Mesh::TrianglesRenumberBySubDomain(bool justcompress){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ReNumberingTheTriangleBySubDomain)*/
+
+		long int verbose=0;
+		long *renu= new long[nbt];
+		register Triangle *t0,*t,*te=triangles+nbt;
+		register long k=0,it,i,j;
+
+		for ( it=0;it<nbt;it++) 
+		 renu[it]=-1; // outside triangle 
+		for ( i=0;i<nbsubdomains;i++)
+		  { 
+			t=t0=subdomains[i].head;
+			if (!t0){ // not empty sub domain
+				_error_("!t0");
+			}
+			do { 
+				long kt = GetId(t);
+				if (kt<0 || kt >= nbt ){
+					_error_("kt<0 || kt >= nbt");
+				}
+				if (renu[kt]!=-1){
+					_error_("renu[kt]!=-1");
+				}
+				renu[kt]=k++;
+			}
+			while (t0 != (t=t->link));
+		  }
+		// take is same numbering if possible    
+		if(justcompress)
+		 for ( k=0,it=0;it<nbt;it++) 
+		  if(renu[it] >=0 ) 
+			renu[it]=k++;
+
+		// put the outside triangles at the end
+		for ( it=0;it<nbt;it++){
+			if (renu[it]==-1) renu[it]=k++;
+		}
+		if (k != nbt){
+			_error_("k != nbt");
+		}
+		// do the change on all the pointeur 
+		for ( it=0;it<nbt;it++)
+		 triangles[it].Renumbering(triangles,te,renu);
+
+		for ( i=0;i<nbsubdomains;i++)
+		 subdomains[i].head=triangles+renu[GetId(subdomains[i].head)];
+
+		// move the Triangles  without a copy of the array 
+		// be carefull not trivial code 
+		for ( it=0;it<nbt;it++) // for all sub cycles of the permutation renu
+		 if (renu[it] >= 0) // a new sub cycle
+			{ 
+			 i=it;
+			 Triangle ti=triangles[i],tj;
+			 while ( (j=renu[i]) >= 0) 
+				{ // i is old, and j is new 
+				 renu[i] = -1; // mark 
+				 tj = triangles[j]; // save new
+				 triangles[j]= ti; // new <- old
+				 i=j;     // next 
+				 ti = tj;
+				}  
+			}
+		delete [] renu;
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::VerticesRenumber{{{*/
+	void Mesh::VerticesRenumber(long * renu) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ReNumberingVertex)*/
+
+		// warning be carfull because pointer
+		// from on mesh to over mesh 
+		//  --  so do ReNumbering at the beginning
+		BamgVertex * ve = vertices+nbv;
+		long it,ie,i;
+
+		_printf_("renumbering triangles\n");
+		for ( it=0;it<nbt;it++) 
+		 triangles[it].Renumbering(vertices,ve,renu);
+
+		_printf_("renumbering edges\n");
+		for ( ie=0;ie<nbe;ie++) 
+		 edges[ie].Renumbering(vertices,ve,renu);
+
+		_printf_("renumbering vertices on geom\n");
+		for (i=0;i< NbVerticesOnGeomVertex;i++)
+		  {
+			BamgVertex *v = VerticesOnGeomVertex[i].meshvertex;
+			if (v>=vertices && v < ve)
+			 VerticesOnGeomVertex[i].meshvertex=vertices+renu[GetId(v)];
+		  }
+
+		_printf_("renumbering vertices on edge\n");
+		for (i=0;i< NbVerticesOnGeomEdge;i++)
+		  {
+			BamgVertex *v =VerticesOnGeomEdge[i].meshvertex;
+			if (v>=vertices && v < ve)
+			 VerticesOnGeomEdge[i].meshvertex=vertices+renu[GetId(v)];
+		  }
+
+		_printf_("renumbering vertices on Bth vertex\n");
+		for (i=0;i< NbVertexOnBThVertex;i++)
+		  {
+			BamgVertex *v=VertexOnBThVertex[i].v;
+			if (v>=vertices && v < ve)
+			 VertexOnBThVertex[i].v=vertices+renu[GetId(v)];
+		  }
+
+		for (i=0;i< NbVertexOnBThEdge;i++)
+		  {
+			BamgVertex *v=VertexOnBThEdge[i].v;
+			if (v>=vertices && v < ve)
+			 VertexOnBThEdge[i].v=vertices+renu[GetId(v)];
+		  }
+
+		// move the Vertices without a copy of the array 
+		// be carefull not trivial code 
+		long j;
+		for ( it=0;it<nbv;it++) // for all sub cycles of the permutation renu
+		 if (renu[it] >= 0) // a new sub cycle
+			{ 
+			 i=it;
+			 BamgVertex ti=vertices[i],tj;
+			 while ( (j=renu[i]) >= 0){
+				 // i is old, and j is new 
+				 renu[i] = -1-renu[i]; // mark 
+				 tj = vertices[j];     // save new
+				 vertices[j]= ti;      // new <- old
+				 i=j;     // next 
+				 ti = tj;
+				}  
+			}
+		if (quadtree){
+			delete quadtree;
+			quadtree = new BamgQuadtree(this);
+		}
+
+		for ( it=0;it<nbv;it++) renu[i]= -renu[i]-1;
+	}
+	/*}}}*/
+/*FUNCTION Mesh::SetIntCoor{{{*/
+void Mesh::SetIntCoor(const char * strfrom) {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SetIntCoor)*/
+
+	/*Set integer coordinate for existing vertices*/
+
+	//Get extrema coordinates of the existing vertices
+	pmin =  vertices[0].r;
+	pmax =  vertices[0].r;
+	long i;
+	for (i=0;i<nbv;i++) {
+		pmin.x = Min(pmin.x,vertices[i].r.x);
+		pmin.y = Min(pmin.y,vertices[i].r.y);
+		pmax.x = Max(pmax.x,vertices[i].r.x);
+		pmax.y = Max(pmax.y,vertices[i].r.y);
+	}
+	R2 DD = (pmax-pmin)*0.05;
+	pmin = pmin-DD;
+	pmax = pmax+DD; 
+
+	//Compute coefIcoor
+	coefIcoor= (MaxICoor)/(Max(pmax.x-pmin.x,pmax.y-pmin.y));
+	if (coefIcoor<=0){
+		_error_("coefIcoor should be positive, a problem in the geometry is likely");
+	}
+
+	// generation of integer coord  
+	for (i=0;i<nbv;i++) {
+		vertices[i].i = R2ToI2(vertices[i].r);    
+	}
+
+	// computation of the det 
+	int number_of_errors=0;
+	for (i=0;i<nbt;i++) {
+		BamgVertex & v0 = triangles[i][0];
+		BamgVertex & v1 = triangles[i][1];
+		BamgVertex & v2 = triangles[i][2];
+
+		//If this is not a boundary triangle
+		if ( &v0 && &v1 &&  &v2 ){
+
+			/*Compute determinant*/
+			triangles[i].det= det(v0,v1,v2);
+
+			/*Check that determinant is positive*/
+			if (triangles[i].det <=0){
+
+				/*increase number_of_errors and print error only for the first 20 triangles*/
+				number_of_errors++;
+				if (number_of_errors<20){
+					_printf_("Area of Triangle " << i+1 << " < 0 (det=" << triangles[i].det << ")\n");
+				}
+			}
+		}
+
+		//else, set as -1
+		else triangles[i].det=-1;
+	}
+
+	if (number_of_errors) _error_("Fatal error: some triangles have negative areas, see above");
+}
+/*}}}*/
+/*FUNCTION Mesh::ShowRegulaty{{{*/
+void  Mesh::ShowRegulaty() const {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr>*/
+
+	const  double  sqrt32=sqrt(3.)*0.5; 
+	const double  aireKh=sqrt32*0.5;
+	D2  Beq(1,0),Heq(0.5,sqrt32);
+	D2xD2 Br(D2xD2(Beq,Heq).t());
+	D2xD2 B1r(Br.inv());
+	double gammamn=1e100,hmin=1e100;
+	double gammamx=0,hmax=0;
+	double beta=1e100;
+	double beta0=0;
+	double  alpha2=0;
+	double area=0,Marea=0;
+	// double cf= double(coefIcoor);
+	// double cf2= 6.*cf*cf;
+	int nt=0;
+	for (int it=0;it<nbt;it++)
+	 if ( triangles[it].link){
+		 Triangle &K=triangles[it];
+		 double  area3= Area2((R2) K[0],(R2) K[1],(R2) K[2])/6.;
+		 area+= area3;
+		 D2xD2 B_Kt(K[0],K[1],K[2]);
+		 D2xD2 B_K(B_Kt.t());
+		 D2xD2 B1K = Br*B_K.inv();
+		 D2xD2 BK =  B_K*B1r;
+		 D2xD2 B1B1 = B1K.t()*B1K;
+		 Metric MK(B1B1.x.x,B1B1.x.y,B1B1.y.y);
+		 EigenMetric VMK(MK);
+		 alpha2 = Max(alpha2,Max(VMK.lambda1/VMK.lambda2,VMK.lambda2/VMK.lambda1));
+		 double betaK=0;
+
+		 for (int j=0;j<3;j++)
+			{
+			 double he= Norme2(R2(K[j],K[(j+1)%3]));
+			 hmin=Min(hmin,he);
+			 hmax=Max(hmax,he);
+			 BamgVertex & v=K[j];
+			 D2xD2 M((Metric)v);
+			 betaK += sqrt(M.det());
+
+			 D2xD2 BMB = BK.t()*M*BK;
+			 Metric M1(BMB.x.x,BMB.x.y,BMB.y.y);
+			 EigenMetric VM1(M1);
+			 gammamn=Min3(gammamn,VM1.lambda1,VM1.lambda2);
+			 gammamx=Max3(gammamx,VM1.lambda1,VM1.lambda2);		
+			}
+		 betaK *= area3;//  1/2 (somme sqrt(det))* area(K)
+		 Marea+= betaK;
+		 beta=min(beta,betaK);
+		 beta0=max(beta0,betaK);
+		}   
+	area*=3; 
+	gammamn=sqrt(gammamn);
+	gammamx=sqrt(gammamx);    
+	_printf_("   Adaptmesh info:\n");
+	_printf_("      number of triangles = " << nt << "\n");
+	_printf_("      hmin = " << hmin << ", hmax=" << hmax << "\n");
+	_printf_("      area = " << area << ", M area = " << Marea << ", M area/( |Khat| nt) = " <<  Marea/(aireKh*nt) << "\n");
+	_printf_("      infinite-regularity(?): min = " << gammamn << ", max = " << gammamx << "\n");
+	_printf_("      anisomax = " << pow(alpha2,0.5) << ", beta max = " << 1./pow(beta/aireKh,0.5) << ", min = " << 1./pow(beta0/aireKh,0.5) << "\n");
+}
+/*}}}*/
+/*FUNCTION Mesh::ShowHistogram{{{*/
+void  Mesh::ShowHistogram() const {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ShowHistogram)*/
+
+	const long kmax=10;
+	const double llmin = 0.5,llmax=2;
+	const double lmin=log(llmin),lmax=log(llmax),delta= kmax/(lmax-lmin);
+	long histo[kmax+1];
+	long i,it,k, nbedges =0;
+	for (i=0;i<=kmax;i++) histo[i]=0;
+	for (it=0;it<nbt;it++)
+	 if ( triangles[it].link) 
+		{
+
+		 for (int j=0;j<3;j++)
+			{
+			 Triangle *ta = triangles[it].TriangleAdj(j);
+			 if ( !ta || !ta->link || GetId(ta) >= it) 
+				{ 
+				 BamgVertex & vP = triangles[it][VerticesOfTriangularEdge[j][0]];
+				 BamgVertex & vQ = triangles[it][VerticesOfTriangularEdge[j][1]];
+				 if ( !& vP || !&vQ) continue;
+				 R2 PQ = vQ.r - vP.r;
+				 double l = log(LengthInterpole(vP,vQ,PQ));
+				 nbedges++;
+				 k = (int) ((l - lmin)*delta);
+				 k = Min(Max(k,0L),kmax);
+				 histo[k]++;
+				}
+			}
+		}  
+	_printf_(" --- Histogram of the unit mesh,  nb of edges = " << nbedges << "\n");
+	_printf_("      length of edge in   | %% of edge  | Nb of edges \n"); 
+	_printf_("      --------------------+-------------+-------------\n"); 
+	for   (i=0;i<=kmax;i++){ 
+		if (i==0) _printf_( "      " << setw(10) << 0.);
+		else      _printf_( "      " << setw(10) << exp(lmin+i/delta));
+		if (i==kmax) _printf_("          +inf   ");
+		else      _printf_( "      " << setw(10) << exp(lmin+(i+1)/delta));
+		_printf_("|  " << setw(10) << (long((10000. * histo[i])/ nbedges)/100.) << " |\n");
+		_printf_("  " << histo[i] << "\n");
+	}
+	_printf_("      --------------------+-------------+-------------\n"); 
+}
+/*}}}*/
+/*FUNCTION Mesh::SmoothingVertex{{{*/
+void Mesh::SmoothingVertex(int nbiter,double omega ) { 
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SmoothingVertex)*/
+
+	long int verbose=0;
+	//  if quatree exist remove it end reconstruct
+	if (quadtree) delete quadtree;
+	quadtree=0;
+	CreateSingleVertexToTriangleConnectivity();
+	Triangle vide; // a triangle to mark the boundary vertex
+	Triangle   ** tstart= new Triangle* [nbv];
+	long i,j,k;
+	//   attention si Background == Triangle alors on ne peut pas utiliser la rechech rapide 
+	if ( this == & BTh)
+	 for ( i=0;i<nbv;i++)
+	  tstart[i]=vertices[i].t;     
+	else 
+	 for ( i=0;i<nbv;i++)
+	  tstart[i]=0;
+	for ( j=0;j<NbVerticesOnGeomVertex;j++ ) 
+	 tstart[ GetId(VerticesOnGeomVertex[j].meshvertex)]=&vide;
+	for ( k=0;k<NbVerticesOnGeomEdge;k++ ) 
+	 tstart[ GetId(VerticesOnGeomEdge[k].meshvertex)]=&vide;
+	if(verbose>2) _printf_("   SmoothingVertex: nb Iteration = " << nbiter << ", Omega=" << omega << "\n");
+	for (k=0;k<nbiter;k++)
+	  {
+		long i,NbSwap =0;
+		double delta =0;
+		for ( i=0;i<nbv;i++)
+		 if (tstart[i] != &vide) // not a boundary vertex 
+		  delta=Max(delta,vertices[i].Smoothing(*this,BTh,tstart[i],omega));
+		if (!nbq)
+		 for ( i=0;i<nbv;i++)
+		  if (tstart[i] != &vide) // not a boundary vertex 
+			NbSwap += vertices[i].Optim(1);
+		if (verbose>3) _printf_("      move max = " << pow(delta,0.5) << ", iteration = " << k << ", nb of swap = " << NbSwap << "\n");
+	  }
+
+	delete [] tstart;
+	if (quadtree) quadtree= new BamgQuadtree(this);
+}
+/*}}}*/
+/*FUNCTION Mesh::SmoothMetric{{{*/
+void Mesh::SmoothMetric(double raisonmax) { 
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/SmoothMetric)*/
+
+	long int verbose=0;
+
+	if(raisonmax<1.1) return;
+	if(verbose > 1) _printf_("   Mesh::SmoothMetric raisonmax = " << raisonmax << "\n");
+	CreateSingleVertexToTriangleConnectivity();
+	long i,j,kch,kk,ip;
+	long *first_np_or_next_t0 = new long[nbv];
+	long *first_np_or_next_t1 = new long[nbv];
+	long Head0 =0,Head1=-1;
+	double logseuil= log(raisonmax);
+
+	for(i=0;i<nbv-1;i++)
+	 first_np_or_next_t0[i]=i+1; 
+	first_np_or_next_t0[nbv-1]=-1;// end;
+	for(i=0;i<nbv;i++)
+	 first_np_or_next_t1[i]=-1;
+	kk=0;
+	while (Head0>=0&& kk++<100) {
+		kch=0;
+		for (i=Head0;i>=0;i=first_np_or_next_t0[ip=i],first_np_or_next_t0[ip]=-1) {
+			//  pour tous les triangles autour du sommet s
+			register Triangle* t= vertices[i].t;
+			if (!t){
+				_error_("!t");
+			}
+			BamgVertex & vi = vertices[i];
+			AdjacentTriangle ta(t,EdgesVertexTriangle[vertices[i].IndexInTriangle][0]);
+			BamgVertex *pvj0 = ta.EdgeVertex(0);
+			while (1) {
+				ta=Previous(Adj(ta));
+				if (vertices+i != ta.EdgeVertex(1)){
+					_error_("vertices+i != ta.EdgeVertex(1)");
+				}
+				BamgVertex & vj = *(ta.EdgeVertex(0));
+				if ( &vj ) {
+					j= &vj-vertices;
+					if (j<0 || j >= nbv){
+						_error_("j<0 || j >= nbv");
+					}
+					R2 Aij = (R2) vj - (R2) vi;
+					double ll =  Norme2(Aij);
+					if (0) {  
+						double hi = ll/vi.m(Aij);
+						double hj = ll/vj.m(Aij);
+						if(hi < hj)
+						  {
+							double dh=(hj-hi)/ll;
+							if (dh>logseuil) {
+								vj.m.IntersectWith(vi.m/(1 +logseuil*ll/hi));
+								if(first_np_or_next_t1[j]<0)
+								 kch++,first_np_or_next_t1[j]=Head1,Head1=j;
+							}
+						  }
+					} 
+					else
+					  {
+						double li = vi.m(Aij);
+						if( vj.m.IntersectWith(vi.m/(1 +logseuil*li)) )
+						 if(first_np_or_next_t1[j]<0) // if the metrix change 
+						  kch++,first_np_or_next_t1[j]=Head1,Head1=j;
+					  }
+				}
+				if  ( &vj ==  pvj0 ) break;
+			}
+		}
+		Head0 = Head1;
+		Head1 = -1;
+		Exchange(first_np_or_next_t0,first_np_or_next_t1);
+	}
+	if(verbose>2) _printf_("      number of iterations = " << kch << "\n"); 
+	delete [] first_np_or_next_t0;
+	delete [] first_np_or_next_t1;
+}
+/*}}}*/
+	/*FUNCTION Mesh::SplitElement{{{*/
+	int  Mesh::SplitElement(int choice){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/SplitElement)*/
+
+		long int verbose=0;
+
+		Direction NoDirOfSearch;
+		const  int withBackground = &BTh != this && &BTh;
+
+		TrianglesRenumberBySubDomain();
+		//int nswap =0;
+		const long nfortria( choice ? 4 : 6);
+		if(withBackground) 
+		  {
+			BTh.SetVertexFieldOn();
+			SetVertexFieldOnBTh();
+		  }
+		else
+		 BTh.SetVertexFieldOn();
+
+		long newnbt=0,newnbv=0;
+		long * kedge = 0;
+		long newnbq=nbq;
+		long * ksplit= 0, * ksplitarray=0;
+		long kkk=0;
+		int ret =0;
+		if (maxnbv<nbv+nbe) return 1;//   
+		// 1) create  the new points by spliting the internal edges 
+		// set the 
+		long nbvold = nbv;
+		long nbtold = nbt;
+		long nbtoutold  = nbtout;
+		long  NbEdgeOnGeom=0;
+		long i;
+
+		nbt = nbt - nbtout; // remove all the  the ouside triangles 
+		long nbtsave = nbt;
+		Triangle * lastT = triangles + nbt;
+		for (i=0;i<nbe;i++)
+		 if(edges[i].GeomEdgeHook) NbEdgeOnGeom++;
+		long newnbe=nbe+nbe;
+		//  long newNbVerticesOnGeomVertex=NbVerticesOnGeomVertex;
+		long newNbVerticesOnGeomEdge=NbVerticesOnGeomEdge+NbEdgeOnGeom;
+		// long newNbVertexOnBThVertex=NbVertexOnBThVertex;
+		long newNbVertexOnBThEdge=withBackground ? NbVertexOnBThEdge+NbEdgeOnGeom:0;
+
+		// do allocation for pointeur to the geometry and background
+		VertexOnGeom * newVerticesOnGeomEdge = new VertexOnGeom[newNbVerticesOnGeomEdge];
+		VertexOnEdge *newVertexOnBThEdge = newNbVertexOnBThEdge ?  new VertexOnEdge[newNbVertexOnBThEdge]:0;
+		if (NbVerticesOnGeomEdge)
+		 memcpy(newVerticesOnGeomEdge,VerticesOnGeomEdge,sizeof(VertexOnGeom)*NbVerticesOnGeomEdge);
+		if (NbVertexOnBThEdge)
+		 memcpy(newVertexOnBThEdge,VertexOnBThEdge,sizeof(VertexOnEdge)*NbVertexOnBThEdge);
+		Edge *newedges = new Edge [newnbe];
+		//  memcpy(newedges,edges,sizeof(Edge)*nbe);
+		SetOfEdges4 * edge4= new SetOfEdges4(nbe,nbv);
+		long k=nbv;
+		long kk=0;
+		long kvb = NbVertexOnBThEdge;
+		long kvg = NbVerticesOnGeomEdge;
+		long ie =0;
+		Edge ** edgesGtoB=0;
+		if (withBackground)
+		 edgesGtoB= BTh.MakeGeomEdgeToEdge();
+		long ferr=0;
+		for (i=0;i<nbe;i++)
+		 newedges[ie].GeomEdgeHook=0;
+
+		for (i=0;i<nbe;i++)
+		  {
+			GeomEdge *ong =  edges[i].GeomEdgeHook;
+
+			newedges[ie]=edges[i];
+			newedges[ie].adj[0]=newedges+(edges[i].adj[0]-edges) ;
+			newedges[ie].adj[1]=newedges + ie +1;
+			R2 A = edges[i][0],B = edges[i][1];
+
+			kk += (i == edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1])));
+			if (ong) // a geometrical edges 
+			  { 
+				if (withBackground){
+					// walk on back ground mesh 
+					//  newVertexOnBThEdge[ibe++] = VertexOnEdge(vertices[k],bedge,absicsseonBedge); 
+					// a faire -- difficile 
+					// the first PB is to now a background edge between the 2 vertices
+					if (!edgesGtoB){
+						_error_("!edgesGtoB");
+					}
+					ong= ProjectOnCurve(*edgesGtoB[Gh.GetId(edges[i].GeomEdgeHook)],
+								edges[i][0],edges[i][1],0.5,vertices[k],
+								newVertexOnBThEdge[kvb],
+								newVerticesOnGeomEdge[kvg++]);
+					vertices[k].ReferenceNumber= edges[i].ReferenceNumber;
+					vertices[k].DirOfSearch =   NoDirOfSearch;        
+					;
+					// get the Info on background mesh 
+					double s =        newVertexOnBThEdge[kvb];
+					BamgVertex &  bv0  = newVertexOnBThEdge[kvb][0];
+					BamgVertex &  bv1  = newVertexOnBThEdge[kvb][1];
+					// compute the metrix of the new points 
+					vertices[k].m =  Metric(1-s,bv0,s,bv1); 
+					kvb++;
+				  }
+				else 
+				  {
+					ong=Gh.ProjectOnCurve(edges[i],
+								0.5,vertices[k],newVerticesOnGeomEdge[kvg++]);
+					// vertices[k].i = R2ToI2( vertices[k].r);
+					vertices[k].ReferenceNumber = edges[i].ReferenceNumber;
+					vertices[k].DirOfSearch = NoDirOfSearch;
+					vertices[k].m =  Metric(0.5,edges[i][0],0.5,edges[i][1]);	      
+				  }  
+			  }
+			else // straigth line edge ---
+			  { 
+				vertices[k].r = ((R2) edges[i][0] + (R2)  edges[i][1] )*0.5;
+				vertices[k].m =  Metric(0.5,edges[i][0],0.5,edges[i][1]);
+				vertices[k].GeomEdgeHook = 0;
+			  }
+			//vertices[k].i = R2ToI2( vertices[k].r);
+			R2 AB =  vertices[k].r;
+			R2 AA = (A+AB)*0.5;
+			R2 BB = (AB+B)*0.5;
+			vertices[k].ReferenceNumber = edges[i].ReferenceNumber;
+			vertices[k].DirOfSearch = NoDirOfSearch;
+
+			newedges[ie].GeomEdgeHook = Gh.Containing(AA,ong);
+			newedges[ie++].v[1]=vertices+k;
+
+			newedges[ie]=edges[i];
+			newedges[ie].adj[0]=newedges + ie -1;
+			newedges[ie].adj[1]=newedges+(edges[i].adj[1]-edges) ;
+			newedges[ie].GeomEdgeHook =  Gh.Containing(BB,ong);
+			newedges[ie++].v[0]=vertices+k;
+			k++;
+		  }
+		if (edgesGtoB) delete [] edgesGtoB;
+		edgesGtoB=0;
+
+		newnbv=k;
+		newNbVerticesOnGeomEdge=kvg;
+		if (newnbv> maxnbv) goto Error;// bug 
+
+		nbv = k;
+
+		kedge = new long[3*nbt+1];
+		ksplitarray = new long[nbt+1];
+		ksplit = ksplitarray +1; // because ksplit[-1] == ksplitarray[0]
+
+		for (i=0;i<3*nbt;i++)
+		 kedge[i]=-1;
+
+		//  
+
+		for (i=0;i<nbt;i++) {
+			Triangle & t = triangles[i];
+			if (!t.link){
+				_error_("!t.link");
+			}
+			for(int j=0;j<3;j++)
+			  {
+				const AdjacentTriangle ta = t.Adj(j);
+				const Triangle & tt = ta;
+				if (&tt >= lastT)
+				 t.SetAdj2(j,0,0);// unset adj
+				const BamgVertex & v0 = t[VerticesOfTriangularEdge[j][0]];
+				const BamgVertex & v1 = t[VerticesOfTriangularEdge[j][1]];
+				long  ke =edge4->SortAndFind(GetId(v0),GetId(v1));
+				if (ke>0) 
+				  {
+					long ii = GetId(tt);
+					int  jj = ta;
+					long ks = ke + nbvold;
+					kedge[3*i+j] = ks;
+					if (ii<nbt) // good triangle
+					 kedge[3*ii+jj] = ks;
+					BamgVertex &A=vertices[ks];
+					double aa,bb,cc,dd;
+					if ((dd=Area2(v0.r,v1.r,A.r)) >=0){
+						// warning PB roundoff error 
+						if (t.link && ( (aa=Area2( A.r    , t[1].r , t[2].r )) < 0.0 
+										||   (bb=Area2( t[0].r , A.r    , t[2].r )) < 0.0  
+										||   (cc=Area2( t[0].r , t[1].r , A.r    )) < 0.0)){
+							_printf_(ke + nbvold << " not in triangle " << i << " In= " << !!t.link << " " << aa << " " << bb << " " << cc << " " << dd << "\n");
+							_error_("Number of triangles with P2 interpolation Problem");
+						}
+					}
+					else {
+						if (tt.link && ( (aa=Area2( A.r     , tt[1].r , tt[2].r )) < 0 
+										||   (bb=Area2( tt[0].r , A.r     , tt[2].r )) < 0 
+										||   (cc=Area2( tt[0].r , tt[1].r , A.r     )) < 0)){
+							_printf_(ke + nbvold << " not in triangle " << ii << " In= " << !!tt.link << " " << aa << " " << bb << " " << cc << " " << dd << "\n");
+							_error_("Number of triangles with P2 interpolation Problem");
+						}
+					} 
+				  }
+			  }
+		}
+
+		for (i=0;i<nbt;i++){
+			ksplit[i]=1; // no split by default
+			const Triangle & t = triangles[ i];
+			int nbsplitedge =0;
+			int nbinvisible =0;
+			int invisibleedge=0;
+			int kkk[3];      
+			for (int j=0;j<3;j++)
+			  {
+				if (t.Hidden(j)) invisibleedge=j,nbinvisible++;
+
+				const AdjacentTriangle ta = t.Adj(j);
+				const Triangle & tt = ta;
+
+				const BamgVertex & v0 = t[VerticesOfTriangularEdge[j][0]];
+				const BamgVertex & v1 = t[VerticesOfTriangularEdge[j][1]];
+				if ( kedge[3*i+j] < 0) 
+				  {
+					long  ke =edge4->SortAndFind(GetId(v0),GetId(v1));
+					if (ke<0) // new 
+					  {
+						if (&tt) // internal triangles all the boundary 
+						  { // new internal edges 
+							long ii = GetId(tt);
+							int  jj = ta;
+
+							kedge[3*i+j]=k;// save the vertex number 
+							kedge[3*ii+jj]=k;
+							if (k<maxnbv) 
+							  {
+								vertices[k].r = ((R2) v0+(R2) v1 )/2;
+								//vertices[k].i = R2ToI2( vertices[k].r);
+								vertices[k].ReferenceNumber=0;
+								vertices[k].DirOfSearch =NoDirOfSearch;
+								vertices[k].m =  Metric(0.5,v0,0.5,v1);
+							  }
+							k++;
+							kkk[nbsplitedge++]=j;		      
+						  } // tt 
+						else
+						 _error_("Bug...");
+					  } // ke<0	       
+					else
+					  { // ke >=0
+						kedge[3*i+j]=nbvold+ke;
+						kkk[nbsplitedge++]=j;// previously splited
+					  }
+				  }
+				else 
+				 kkk[nbsplitedge++]=j;// previously splited
+
+			  } 
+			if (nbinvisible>=2){
+				_error_("nbinvisible>=2");
+			}
+			switch (nbsplitedge) {
+				case 0: ksplit[i]=10; newnbt++; break;   // nosplit
+				case 1: ksplit[i]=20+kkk[0];newnbt += 2; break; // split in 2 
+				case 2: ksplit[i]=30+3-kkk[0]-kkk[1];newnbt += 3; break; // split in 3 
+				case 3:
+						  if (nbinvisible) ksplit[i]=40+invisibleedge,newnbt += 4;
+						  else   ksplit[i]=10*nfortria,newnbt+=nfortria;
+						  break;
+			} 
+			if (ksplit[i]<40){
+				_error_("ksplit[i]<40");
+			}
+		  }
+		//  now do the element split
+		newnbq = 4*nbq;
+		nbv = k;
+		kkk = nbt;
+		ksplit[-1] = nbt;
+		// look on  old true  triangles 
+
+		for (i=0;i<nbtsave;i++){
+			int  nbmkadj=0;
+			long mkadj [100];
+			mkadj[0]=i;
+			long kk=ksplit[i]/10;
+			int  ke=(int) (ksplit[i]%10);
+			if (kk>=7 || kk<=0){
+				_error_("kk>=7 || kk<=0");
+			}
+
+			// def the numbering   k (edge) i vertex 
+			int k0 = ke;
+			int k1 = NextEdge[k0];
+			int k2 = PreviousEdge[k0];
+			int i0 = OppositeVertex[k0];
+			int i1 = OppositeVertex[k1];
+			int i2 = OppositeVertex[k2];
+
+			Triangle &t0=triangles[i];
+			BamgVertex * v0=t0(i0);           
+			BamgVertex * v1=t0(i1);           
+			BamgVertex * v2=t0(i2);
+
+			if (nbmkadj>=10){
+				_error_("nbmkadj>=10");
+			}
+			// --------------------------
+			AdjacentTriangle ta0(t0.Adj(i0)),ta1(t0.Adj(i1)),ta2(t0.Adj(i2));
+			// save the flag Hidden
+			int hid[]={t0.Hidden(0),t0.Hidden(1),t0.Hidden(2)};
+			// un set all adj -- save Hidden flag --
+			t0.SetAdj2(0,0,hid[0]);
+			t0.SetAdj2(1,0,hid[1]);
+			t0.SetAdj2(2,0,hid[2]);
+			// --  remake 
+			switch  (kk) {
+				case 1: break;// nothing 
+				case 2: // 
+						  {
+							Triangle &t1=triangles[kkk++];
+							t1=t0;
+							if (kedge[3*i+i0]<0){
+								_error_("kedge[3*i+i0]<0");
+							}
+							BamgVertex * v3 = vertices + kedge[3*i+k0];
+
+							t0(i2) = v3;
+							t1(i1) = v3;
+							t0.SetAllFlag(k2,0);
+							t1.SetAllFlag(k1,0);
+						  } 
+						break; 
+				case 3: //
+						  {
+							Triangle &t1=triangles[kkk++];
+							Triangle &t2=triangles[kkk++];
+							t2=t1=t0;
+							if (kedge[3*i+k1]<0){
+								_error_("kedge[3*i+k1]<0");
+							}
+							if (kedge[3*i+k2]<0){
+								_error_("kedge[3*i+k2]<0");
+							}
+
+							BamgVertex * v01 = vertices + kedge[3*i+k2];
+							BamgVertex * v02 = vertices + kedge[3*i+k1]; 
+							t0(i1) = v01; 
+							t0(i2) = v02; 
+							t1(i2) = v02;
+							t1(i0) = v01; 
+							t2(i0) = v02; 
+							t0.SetAllFlag(k0,0);
+							t1.SetAllFlag(k1,0);
+							t1.SetAllFlag(k0,0);
+							t2.SetAllFlag(k2,0);
+						  } 
+						break;
+				case 4: // 
+				case 6: // split in 4 
+						  {
+							Triangle &t1=triangles[kkk++];
+							Triangle &t2=triangles[kkk++];
+							Triangle &t3=triangles[kkk++];
+							t3=t2=t1=t0;
+							if (kedge[3*i+k0] <0 || kedge[3*i+k1]<0 || kedge[3*i+k2]<0){
+								_error_("kedge[3*i+k0] <0 || kedge[3*i+k1]<0 || kedge[3*i+k2]<0");
+							}
+							BamgVertex * v12 = vertices + kedge[3*i+k0];
+							BamgVertex * v02 = vertices + kedge[3*i+k1]; 
+							BamgVertex * v01 = vertices + kedge[3*i+k2];
+							t0(i1) = v01;
+							t0(i2) = v02;
+							t0.SetAllFlag(k0,hid[k0]);
+
+							t1(i0) = v01;
+							t1(i2) = v12;
+							t0.SetAllFlag(k1,hid[k1]);
+
+							t2(i0) = v02;
+							t2(i1) = v12;
+							t2.SetAllFlag(k2,hid[k2]);
+
+							t3(i0) = v12;
+							t3(i1) = v02;
+							t3(i2) = v01;
+
+							t3.SetAllFlag(0,hid[0]);	   
+							t3.SetAllFlag(1,hid[1]);	   
+							t3.SetAllFlag(2,hid[2]);
+
+							if ( kk == 6)
+							  {
+
+								Triangle &t4=triangles[kkk++];
+								Triangle &t5=triangles[kkk++];
+
+								t4 = t3;
+								t5 = t3;
+
+								t0.SetHidden(k0);
+								t1.SetHidden(k1);
+								t2.SetHidden(k2);
+								t3.SetHidden(0);
+								t4.SetHidden(1);
+								t5.SetHidden(2);
+
+								if (nbv < maxnbv ) 
+								  {
+									vertices[nbv].r = ((R2) *v01 + (R2) *v12  + (R2) *v02 ) / 3.0;
+									vertices[nbv].ReferenceNumber =0;
+									vertices[nbv].DirOfSearch =NoDirOfSearch;
+									//vertices[nbv].i = R2ToI2(vertices[nbv].r);
+									double a3[]={1./3.,1./3.,1./3.};
+									vertices[nbv].m = Metric(a3,v0->m,v1->m,v2->m);
+									BamgVertex * vc =  vertices +nbv++;
+									t3(i0) = vc;
+									t4(i1) = vc;
+									t5(i2) = vc;
+
+								  }
+								else
+								 goto Error; 
+							  }
+
+						  } 
+						break;         
+			}
+
+			// save all the new triangles
+			mkadj[nbmkadj++]=i;
+			long jj;
+			if (t0.link) 
+			 for (jj=nbt;jj<kkk;jj++)
+				{
+				 triangles[jj].link=t0.link;
+				 t0.link= triangles+jj;
+				 mkadj[nbmkadj++]=jj;
+				}
+			if (nbmkadj>13){// 13 = 6 + 4 +
+				_error_("nbmkadj>13");
+			}
+
+			if (kk==6)  newnbq+=3;
+			for (jj=ksplit[i-1];jj<kkk;jj++) nbt = kkk;
+			ksplit[i]= nbt; // save last adresse of the new triangles
+			kkk = nbt;
+		  }
+
+		for (i=0;i<nbv;i++) vertices[i].m = vertices[i].m*2.;
+
+		if(withBackground)
+		 for (i=0;i<BTh.nbv;i++)
+		  BTh.vertices[i].m =  BTh.vertices[i].m*2.;
+
+		ret = 2;
+		if (nbt>= maxnbt) goto Error; // bug 
+		if (nbv>= maxnbv) goto Error; // bug 
+		// generation of the new triangles 
+
+		SetIntCoor("In SplitElement"); 
+
+		CreateSingleVertexToTriangleConnectivity();
+		if(withBackground)
+		 BTh.CreateSingleVertexToTriangleConnectivity();
+
+		delete [] edges;
+		edges = newedges;
+		nbe = newnbe;
+		nbq = newnbq;
+
+		for (i=0;i<nbsubdomains;i++)
+		  { 
+			long k = subdomains[i].edge- edges;
+			subdomains[i].edge =  edges+2*k; // spilt all edge in 2 
+		  }
+
+		if (ksplitarray) delete [] ksplitarray;
+		if (kedge) delete [] kedge;
+		if (edge4) delete edge4;
+		if (VerticesOnGeomEdge) delete [] VerticesOnGeomEdge;
+		VerticesOnGeomEdge= newVerticesOnGeomEdge;
+		if(VertexOnBThEdge) delete []  VertexOnBThEdge;
+		VertexOnBThEdge = newVertexOnBThEdge;
+		NbVerticesOnGeomEdge = newNbVerticesOnGeomEdge;
+		NbVertexOnBThEdge=newNbVertexOnBThEdge;
+		//  CreateSingleVertexToTriangleConnectivity();
+
+		ReconstructExistingMesh();
+
+		if (verbose>2){
+			_printf_("   number of quadrilaterals    = " << nbq << "\n");
+			_printf_("   number of triangles         = " << nbt-nbtout- nbq*2 << "\n");
+			_printf_("   number of outside triangles = " << nbtout << "\n");
+		}
+
+		return 0; //ok
+
+Error:
+		nbv = nbvold;
+		nbt = nbtold;
+		nbtout = nbtoutold;
+		// cleaning memory ---
+		delete [] newedges;
+		if (ksplitarray) delete [] ksplitarray;
+		if (kedge) delete [] kedge;
+		if (newVerticesOnGeomEdge) delete [] newVerticesOnGeomEdge;
+		if (edge4) delete edge4;
+		if(newVertexOnBThEdge) delete []  newVertexOnBThEdge;
+
+		return ret; // ok 
+	}
+	/*}}}*/
+/*FUNCTION Mesh::SplitInternalEdgeWithBorderVertices{{{*/
+long  Mesh::SplitInternalEdgeWithBorderVertices(){
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SplitInternalEdgeWithBorderVertices)*/
+
+	long NbSplitEdge=0;
+	SetVertexFieldOn();  
+	long it;
+	long nbvold=nbv;
+	long int verbose=2;
+	for (it=0;it<nbt;it++){
+		Triangle &t=triangles[it];
+		if (t.link)
+		 for (int j=0;j<3;j++)
+		  if(!t.Locked(j) && !t.Hidden(j)){
+			  Triangle &tt = *t.TriangleAdj(j);
+			  if ( &tt && tt.link && it < GetId(tt)) 
+				 { // an internal edge 
+				  BamgVertex &v0 = t[VerticesOfTriangularEdge[j][0]];
+				  BamgVertex &v1 = t[VerticesOfTriangularEdge[j][1]];
+				  if (v0.GeomEdgeHook && v1.GeomEdgeHook){
+					  R2 P= ((R2) v0 + (R2) v1)*0.5;
+					  if ( nbv<maxnbv) {
+						  vertices[nbv].r = P;
+						  vertices[nbv++].m = Metric(0.5,v0.m,0.5,v1.m);
+						  vertices[nbv].ReferenceNumber=0;
+						  vertices[nbv].DirOfSearch = NoDirOfSearch ;
+					  }
+					  NbSplitEdge++;
+				  }
+				 }
+		  }
+	}
+	CreateSingleVertexToTriangleConnectivity();    
+	if (nbvold!=nbv){
+		long  iv = nbvold;
+		long NbSwap = 0;
+		Icoor2 det3[3];  
+		for (int i=nbvold;i<nbv;i++) {// for all the new point
+			BamgVertex & vi = vertices[i];
+			vi.i = R2ToI2(vi.r);
+			vi.r = I2ToR2(vi.i);
+
+			// a good new point 
+			vi.ReferenceNumber=0; 
+			vi.DirOfSearch =NoDirOfSearch;
+			Triangle *tcvi = TriangleFindFromCoord(vi.i,det3);
+			if (tcvi && !tcvi->link) {
+				_printf_("problem inserting point in SplitInternalEdgeWithBorderVertices (tcvj && !tcvj->link)\n");
+			}
+
+			quadtree->Add(vi);
+			if (!tcvi || tcvi->det<0){// internal
+				_error_("!tcvi || tcvi->det < 0");
+			}
+			AddVertex(vi,tcvi,det3);
+			NbSwap += vi.Optim(1);          
+			iv++;
+		}
+		if (verbose>3) {
+			_printf_("   number of points: " << iv << "\n");
+			_printf_("   number of swap to  split internal edges with border vertices: " << NbSwap << "\n");
+			nbv = iv;
+		}
+	}
+	if (NbSplitEdge>nbv-nbvold) _printf_("WARNING: not enough vertices  to split all internal edges, we lost " << NbSplitEdge - ( nbv-nbvold) << " edges...\n");
+	if (verbose>2) _printf_("SplitInternalEdgeWithBorderVertices: Number of splited edge " << NbSplitEdge << "\n");
+
+	return  NbSplitEdge;
+}
+/*}}}*/
+/*FUNCTION Mesh::ToI2{{{*/
+I2 Mesh::R2ToI2(const R2 & P) const {
+	return  I2( (Icoor1) (coefIcoor*(P.x-pmin.x)),(Icoor1) (coefIcoor*(P.y-pmin.y)) );
+}
+/*}}}*/
+/*FUNCTION Mesh::ToR2{{{*/
+R2 Mesh::I2ToR2(const I2 & P) const {
+	return  R2( (double) P.x/coefIcoor+pmin.x, (double) P.y/coefIcoor+pmin.y);
+}
+/*}}}*/
+/*FUNCTION Mesh::TriangleFindFromCoord{{{*/
+Triangle * Mesh::TriangleFindFromCoord(const I2 & B,Icoor2 det3[3], Triangle *tstart) const {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindTriangleContening)*/
+
+	Triangle * t=0;	
+	int j,jp,jn,jj;
+	int counter;
+
+	/*Get starting triangle. Take tsart if provided*/
+	if (tstart) t=tstart;
+
+	/*Else find the closest Triangle using the quadtree*/
+	else {
+
+		/*Check that the quadtree does exist*/
+		if (!quadtree) _error_("no starting triangle provided and no quadtree available");
+
+		/*Call NearestVertex*/
+		BamgVertex *a = quadtree->NearestVertex(B.x,B.y) ;
+
+		/*Check output (Vertex a)*/
+		if (!a)    _error_("problem while trying to find nearest vertex from a given point. No output found");
+		if (!a->t) _error_("no triangle is associated to vertex number " << GetId(a)+1 << " (orphan?)");
+		_assert_(a>=vertices && a<vertices+nbv);
+
+		/*Get starting triangle*/
+		t = a->t;
+		_assert_(t>=triangles && t<triangles+nbt);
+	}
+
+	Icoor2  detop ;
+
+	/*initialize number of test triangle*/
+	counter=0; 
+
+	/*The initial triangle might be outside*/
+	while (t->det < 0){ 
+
+		/*Get a real vertex from this triangle (k0)*/
+		int k0=(*t)(0)?(((*t)(1)?((*t)(2)?-1:2):1)):0;
+		_assert_(k0>=0);// k0 the NULL vertex
+		int k1=NextVertex[k0],k2=PreviousVertex[k0];
+		det3[k0]=det(B,(*t)[k1],(*t)[k2]);
+		det3[k1]=det3[k2]=-1;     
+		if (det3[k0] > 0) // outside B 
+		 return t; 
+		t = t->TriangleAdj(OppositeEdge[k0]);
+		counter++;
+		_assert_(counter<2);
+	}
+
+	jj=0;
+	detop = det(*(*t)(VerticesOfTriangularEdge[jj][0]),*(*t)(VerticesOfTriangularEdge[jj][1]),B);
+
+	while(t->det>0) { 
+
+		/*Increase counter*/
+		if (++counter>=10000) _error_("Maximum number of iteration reached (threshold = " << counter << ").");
+
+		j= OppositeVertex[jj];
+		det3[j] = detop;  //det(*b,*s1,*s2);
+		jn = NextVertex[j];
+		jp = PreviousVertex[j];
+		det3[jp]= det(*(*t)(j),*(*t)(jn),B);
+		det3[jn] = t->det-det3[j] -det3[jp];
+
+		// count the number k of  det3 <0
+		int k=0,ii[3];
+		if (det3[0] < 0 ) ii[k++]=0; 
+		if (det3[1] < 0 ) ii[k++]=1;
+		if (det3[2] < 0 ) ii[k++]=2;
+		// 0 => ok
+		// 1 => go in way 1
+		// 2 => two way go in way 1 or 2 randomly
+
+		if (k==0) break;
+		if (k==2 && BinaryRand()) Exchange(ii[0],ii[1]);
+		_assert_(k<3);
+		AdjacentTriangle t1 = t->Adj(jj=ii[0]);
+		if ((t1.det() < 0 ) && (k == 2))
+		 t1 = t->Adj(jj=ii[1]);
+		t=t1;
+		j=t1;// for optimisation we now the -det[OppositeVertex[j]];
+		detop = -det3[OppositeVertex[jj]];
+		jj = j;
+	}
+
+	if (t->det<0) // outside triangle 
+	 det3[0]=det3[1]=det3[2]=-1,det3[OppositeVertex[jj]]=detop;
+	return t;
+}
+/*}}}*/
+/*FUNCTION Mesh::TriangleIntNumbering{{{*/
+void Mesh::TriangleIntNumbering(long* renumbering){
+
+	long num=0;
+	for (int i=0;i<nbt;i++){
+		if (triangles[i].det>0) renumbering[i]=num++;
+		else renumbering[i]=-1;
+	}
+	return;   
+}
+/*}}}*/
+/*FUNCTION Mesh::TriangleReferenceList{{{*/
+long  Mesh::TriangleReferenceList(long* reft) const {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ConsRefTriangle)*/
+
+	long int verbose=0;
+	register Triangle *t0,*t;
+	register long k=0, num;   
+
+	//initialize all triangles as -1 (outside)
+	for (int it=0;it<nbt;it++) reft[it]=-1;
+
+	//loop over all subdomains
+	for (int i=0;i<nbsubdomains;i++){ 
+
+		//first triangle of the subdomain i
+		t=t0=subdomains[i].head;
+
+		//check that the subdomain is not empty
+		if (!t0){ _error_("At least one subdomain is empty");}
+
+		//loop
+		do{
+			k++;
+
+			//get current triangle number
+			num = GetId(t);
+
+			//check that num is in [0 nbt[
+			_assert_(num>=0 && num<nbt);
+
+			//reft of this triangle is the subdomain number
+			reft[num]=i;
+
+		} while (t0 != (t=t->link));
+		//stop when all triangles of subdomains have been tagged
+
+	}
+	return k;   
+}
+/*}}}*/
+/*FUNCTION Mesh::Triangulate{{{*/
+void Mesh::Triangulate(double* x,double* y,int nods){
+
+	int verbose=0;
+	int i;
+	Metric M1(1);
+
+	/*Initialize mesh*/
+	Init(nods);//this resets nbv to 0
+	nbv=nods;
+
+	//Vertices
+	if(verbose) _printf_("Reading vertices (" << nbv << ")\n");
+	for (i=0;i<nbv;i++){
+		vertices[i].r.x=x[i];
+		vertices[i].r.y=y[i];
+		vertices[i].ReferenceNumber=1;
+		vertices[i].DirOfSearch =NoDirOfSearch;
+		vertices[i].m=M1;
+		vertices[i].color=0;
+	}
+	maxnbt=2*maxnbv-2; // for filling The Holes and quadrilaterals 
+
+	/*Insert Vertices*/
+	Insert();
+}
+/*}}}*/
+	/*FUNCTION Mesh::TriangulateFromGeom0{{{*/
+	void Mesh::TriangulateFromGeom0(BamgOpts* bamgopts){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/GeomToTriangles0)*/
+		/*Generate mesh from geometry*/
+
+		/*Intermediaries*/
+		int                i,k;
+		int                nbcurves    = 0;
+		int                NbNewPoints,NbEdgeCurve;
+		double             lcurve,lstep,s;
+		const int          MaxSubEdge  = 10;
+
+		R2          AB;
+		GeomVertex *a, *b;
+		BamgVertex *va,*vb;
+		GeomEdge   *e;
+
+		// add a ref to GH to make sure that it is not destroyed by mistake
+		Gh.NbRef++;
+
+		/*Get options*/
+		int verbose=bamgopts->verbose;
+
+		//build background mesh flag (1 if background, else 0)
+		bool background=(&BTh != this);
+
+		/*Build VerticesOnGeomVertex*/
+
+		//Compute the number of geometrical vertices that we are going to use to mesh
+		for (i=0;i<Gh.nbv;i++){
+			if (Gh[i].Required()) NbVerticesOnGeomVertex++;
+		}
+		//allocate
+		VerticesOnGeomVertex = new VertexOnGeom[NbVerticesOnGeomVertex];  
+		if(NbVerticesOnGeomVertex >= maxnbv) _error_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
+		_assert_(nbv==0);
+		//Build VerticesOnGeomVertex
+		for (i=0;i<Gh.nbv;i++){
+			/* Add vertex only if required*/
+			if (Gh[i].Required()) {//Gh  vertices Required
+
+				//Add the vertex
+				_assert_(nbv<maxnbv);
+				vertices[nbv]=Gh[i];
+
+				//Add pointer from geometry (Gh) to vertex from mesh (Th)
+				Gh[i].MeshVertexHook=vertices+nbv;
+
+				//Build VerticesOnGeomVertex for current point
+				VerticesOnGeomVertex[nbv]=VertexOnGeom(*Gh[i].MeshVertexHook,Gh[i]);
+
+				//nbv increment
+				nbv++;
+			}
+		}
+
+		/*Build VerticesOnGeomEdge*/
+
+		//check that edges is still empty (Init)
+		_assert_(!edges);
+
+		/* Now we are going to create the first edges corresponding
+		 * to the one present in the geometry provided.
+		 * We proceed in 2 steps
+		 *  -step 0: we count all the edges
+		 *           we allocate the number of edges at the end of step 0
+		 *  -step 1: the edges are created */
+		for (int step=0;step<2;step++){
+
+			//initialize number of edges and number of edges max
+			long nbex=0;
+			nbe=0;
+			long NbVerticesOnGeomEdge0=NbVerticesOnGeomEdge;
+			Gh.UnMarkEdges();	
+			nbcurves=0;
+
+			//go through the edges of the geometry
+			for (i=0;i<Gh.nbe;i++){
+
+				//ei = current Geometrical edge
+				GeomEdge &ei=Gh.edges[i];   
+
+				//loop over the two vertices of the edge ei
+				for(int j=0;j<2;j++) {
+
+					/*Take only required vertices (corner->beginning of a new curve)*/
+					if (!ei.Mark() && ei[j].Required()){ 
+
+						long  nbvend=0;
+						Edge* PreviousNewEdge=NULL;
+						lstep = -1;
+
+						/*If Edge is required (do that only once for the 2 vertices)*/
+						if(ei.Required()){
+							if (j==0){
+								//do not create internal points if required (take it as is)
+								if(step==0) nbe++;
+								else{ 
+									e=&ei;
+									a=ei(0);
+									b=ei(1);
+
+									//check that edges has been allocated
+									_assert_(edges);
+									edges[nbe].v[0]=a->MeshVertexHook;
+									edges[nbe].v[1]=b->MeshVertexHook;;
+									edges[nbe].ReferenceNumber = e->ReferenceNumber;
+									edges[nbe].GeomEdgeHook = e;
+									edges[nbe].adj[0] = 0;
+									edges[nbe].adj[1] = 0;
+									nbe++;
+								}
+							}
+						}
+
+						/*If Edge is not required: we are on a curve*/
+						else {
+							for (int kstep=0;kstep<=step;kstep++){
+								//kstep=0, compute number of edges (discretize curve)
+								//kstep=1  create the points and edge
+								PreviousNewEdge=0;
+								NbNewPoints=0;
+								NbEdgeCurve=0;
+								if (nbvend>=maxnbv) _error_("maximum number of vertices too low! Check the domain outline or increase maxnbv");
+								lcurve =0;
+								s = lstep; //-1 initially, then length of each sub edge
+
+								/*reminder: i = edge number, j=[0;1] vertex index in edge*/
+								k=j;            // k = vertex index in edge (0 or 1)
+								e=&ei;          // e = reference of current edge
+								a=ei(k);        // a = pointer toward the kth vertex of the current edge
+								va = a->MeshVertexHook; // va = pointer toward mesh vertex associated
+								e->SetMark();   // Mark edge
+
+								/*Loop until we reach the end of the curve*/
+								for(;;){ 
+									k = 1-k;            // other vertx index of the curve
+									b = (*e)(k);        // b = pointer toward the other vertex of the current edge
+									AB= b->r - a->r;   // AB = vector of the current edge
+									Metric MA = background ? BTh.MetricAt(a->r) :a->m ;  //Get metric associated to A
+									Metric MB = background ? BTh.MetricAt(b->r) :b->m ;  //Get metric associated to B
+									double ledge = (MA(AB) + MB(AB))/2;                  //Get edge length in metric
+
+									/* We are now creating the mesh edges from the geometrical edge selected above.
+									 * The edge will be divided according to the metric previously computed and cannot
+									 * be divided more than 10 times (MaxSubEdge). */
+
+									//By default, there is only one subedge that is the geometrical edge itself
+									int NbSubEdge = 1;
+
+									//initialize lSubEdge, holding the length of each subedge (cannot be higher than 10)
+									double lSubEdge[MaxSubEdge];
+
+									//Build Subedges according to the edge length
+									if (ledge < 1.5){
+										//if ledge < 1.5 (between one and 2), take the edge as is
+										lSubEdge[0] = ledge;
+									}
+									//else, divide the edge
+									else {
+										//compute number of subedges (division of the edge), Maximum is 10
+										NbSubEdge = Min( MaxSubEdge, (int) (ledge +0.5));
+										/*Now, we are going to divide the edge according to the metric.
+										 * Get segment by sement along the edge.
+										 * Build lSubEdge, which holds the distance between the first vertex
+										 * of the edge and the next point on the edge according to the 
+										 * discretization (each SubEdge is AB)*/
+										R2 A,B;
+										A=a->r;
+										Metric MAs=MA,MBs;
+										ledge=0; 
+										double x =0, xstep= 1./NbSubEdge;
+										for (int kk=0; kk < NbSubEdge; kk++,A=B,MAs=MBs ) {
+											x += xstep;
+											B =  e->F(k ? x : 1-x);
+											MBs= background ? BTh.MetricAt(B) : Metric(1-x,MA,x,MB);
+											AB = A-B;
+											lSubEdge[kk]=(ledge+=(MAs(AB)+MBs(AB))/2);
+										}
+									}
+
+									double lcurveb = lcurve+ledge;
+
+									/*Now, create corresponding points*/
+									while(s>=lcurve && s<=lcurveb && nbv<nbvend){
+
+										/*Schematic of current curve
+										 *
+										 *  a                   vb                  b          // vertex
+										 *  0              ll0     ll1              ledge      // length from a
+										 *  + --- + - ... - + --S-- + --- + - ... - +          // where is S
+										 *  0              kk0     kk1              NbSubEdge  // Sub edge index
+										 *
+										 */
+
+										double ss = s-lcurve;
+
+										/*Find the SubEdge containing ss using Dichotomy*/
+										int kk0=-1,kk1=NbSubEdge-1,kkk;
+										double ll0=0,ll1=ledge,llk;
+										while (kk1-kk0>1){
+											if (ss < (llk=lSubEdge[kkk=(kk0+kk1)/2]))
+											 kk1=kkk,ll1=llk;
+											else
+											 kk0=kkk,ll0=llk;
+										}
+										_assert_(kk1!=kk0);
+
+										/*Curvilinear coordinate in [0 1] of ss in current edge*/
+										// WARNING: This is what we would do
+										// ssa = (ss-ll0)/(ll1-ll0);
+										// aa = (kk0+ssa)/NbSubEdge
+										// This is what Bamg does:
+										double sbb = (ss-ll0)/(ll1-ll0);
+										/*Curvilinear coordinate in [0 1] of ss in current curve*/
+										double bb = (kk1+sbb)/NbSubEdge;
+										double aa = 1-bb;
+
+										// new vertex on edge
+										vb = &vertices[nbv++];
+										vb->m = Metric(aa,a->m,bb,b->m);
+										vb->ReferenceNumber = e->ReferenceNumber;
+										vb->DirOfSearch =NoDirOfSearch;
+										double abcisse = k ? bb : aa;
+										vb->r =  e->F(abcisse);
+										VerticesOnGeomEdge[NbVerticesOnGeomEdge++]= VertexOnGeom(*vb,*e,abcisse);        
+
+										// to take into account the direction of the edge
+										s += lstep;
+										edges[nbe].v[0]=va;
+										edges[nbe].v[1]=vb;
+										edges[nbe].ReferenceNumber =e->ReferenceNumber;
+										edges[nbe].GeomEdgeHook = e;
+										edges[nbe].adj[0] = PreviousNewEdge;
+										if(PreviousNewEdge) PreviousNewEdge->adj[1]=&edges[nbe];
+										PreviousNewEdge=edges+nbe;
+										nbe++;
+										va = vb;
+									}
+
+									/*We just added one edge to the curve: Go to the next one*/
+									lcurve = lcurveb;
+									e->SetMark();
+									a=b;
+
+									/*If b is required, we are on a new curve->break*/
+									if (b->Required()) break;
+									int kprev=k;
+									k = e->AdjVertexIndex[kprev];// next vertices
+									e = e->Adj[kprev];
+									_assert_(e);
+								}// for(;;)
+								vb = b->MeshVertexHook;
+
+								/*Number of edges in the last disretized curve*/
+								NbEdgeCurve = Max((long) (lcurve +0.5), (long) 1);
+								/*Number of internal vertices in the last disretized curve*/
+								NbNewPoints = NbEdgeCurve-1;
+								if(!kstep){
+									NbVerticesOnGeomEdge0 += NbNewPoints;
+									nbcurves++;
+								}
+								nbvend=nbv+NbNewPoints; 
+								lstep = lcurve / NbEdgeCurve; //approximately one
+							}// end of curve --
+							if (edges) { // last edges of the curves 
+								edges[nbe].v[0]=va;
+								edges[nbe].v[1]=vb;
+								edges[nbe].ReferenceNumber = e->ReferenceNumber;
+								edges[nbe].GeomEdgeHook = e;
+								edges[nbe].adj[0] = PreviousNewEdge;
+								edges[nbe].adj[1] = 0;
+								if(PreviousNewEdge) PreviousNewEdge->adj[1] = & edges[nbe];
+								nbe++;
+							}
+							else nbe += NbEdgeCurve;
+						} // end on  curve ---
+					}
+				}
+			} // for (i=0;i<nbe;i++)
+			if(!step) {
+				_assert_(!edges);
+				_assert_(!VerticesOnGeomEdge);
+
+				edges = new Edge[nbex=nbe];
+				if(NbVerticesOnGeomEdge0) VerticesOnGeomEdge = new VertexOnGeom[NbVerticesOnGeomEdge0];
+
+				// do the vertex on a geometrical vertex
+				_assert_(VerticesOnGeomEdge || NbVerticesOnGeomEdge0==0);
+				NbVerticesOnGeomEdge0 = NbVerticesOnGeomEdge;       
+			}
+			else{
+				_assert_(NbVerticesOnGeomEdge==NbVerticesOnGeomEdge0);
+			}
+		}
+
+		//Insert points inside existing triangles
+		if (verbose>4) _printf_("      -- current number of vertices = " << nbv << "\n");
+		if (verbose>3) _printf_("      Creating initial Constrained Delaunay Triangulation...\n");
+		if (verbose>3) _printf_("         Inserting boundary points\n");
+		Insert();
+
+		//Force the boundary
+		if (verbose>3) _printf_("         Forcing boundaries\n");
+		ForceBoundary();
+
+		//Extract SubDomains
+		if (verbose>3) _printf_("         Extracting subdomains\n");
+		FindSubDomain();
+
+		if (verbose>3) _printf_("      Inserting internal points\n");
+		NewPoints(*this,bamgopts,0) ;
+		if (verbose>4) _printf_("      -- current number of vertices = " << nbv << "\n");
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::TriangulateFromGeom1{{{*/
+	void Mesh::TriangulateFromGeom1(BamgOpts* bamgopts,int KeepVertices){ 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/GeomToTriangles1)*/
+
+		/*Get options*/
+		int verbose=bamgopts->verbose;
+
+		Gh.NbRef++;// add a ref to Gh
+
+		/************************************************************************* 
+		 * method in 2 steps
+		 * 1 - compute the number of new edges to allocate
+		 * 2 - construct the edges
+		 * remark:
+		 * in this part we suppose to have a background mesh with the same geometry 
+		 * 
+		 * To construct the discretization of the new mesh we have to 
+		 * rediscretize the boundary of background Mesh 
+		 * because we have only the pointeur from the background mesh to the geometry.
+		 * We need the abcisse of the background mesh vertices on geometry
+		 * so a vertex is 
+		 * 0 on GeomVertex ;
+		 * 1 on GeomEdge + abcisse
+		 * 2 internal 
+		 *************************************************************************/
+
+		//Check that background mesh and current mesh do have the same geometry
+		_assert_(&BTh.Gh==&Gh);
+		BTh.NbRef++; // add a ref to BackGround Mesh
+
+		//Initialize new mesh
+		BTh.SetVertexFieldOn();
+		int* bcurve = new int[Gh.nbcurves]; // 
+
+		/* There are 2 ways to make the loop 
+		* 1) on the geometry 
+		* 2) on the background mesh
+		*  if you do the loop on geometry, we don't have the pointeur on background,
+		*  and if you do the loop in background we have the pointeur on geometry
+		* so do the walk on  background */
+
+		NbVerticesOnGeomVertex=0;
+		NbVerticesOnGeomEdge=0;
+
+		/*STEP 1 copy of Required vertices*/
+
+		int i; 
+		for (i=0;i<Gh.nbv;i++) if (Gh[i].Required()) NbVerticesOnGeomVertex++;
+		printf("\n");
+		if(NbVerticesOnGeomVertex >= maxnbv){
+			_error_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
+		}
+
+		VerticesOnGeomVertex = new VertexOnGeom[  NbVerticesOnGeomVertex];
+		VertexOnBThVertex    = new VertexOnVertex[NbVerticesOnGeomVertex];
+
+		//At this point there is NO vertex but vertices should have been allocated by Init
+		_assert_(vertices);
+		for (i=0;i<Gh.nbv;i++){
+			if (Gh[i].Required()) {//Gh vertices Required
+				vertices[nbv]  =Gh[i];
+				vertices[nbv].i=I2(0,0);
+				Gh[i].MeshVertexHook = vertices + nbv;// save Geom -> Th
+				VerticesOnGeomVertex[nbv]= VertexOnGeom(vertices[nbv],Gh[i]);
+				nbv++;
+			}
+			else Gh[i].MeshVertexHook=0;
+		} 
+		for (i=0;i<BTh.NbVerticesOnGeomVertex;i++){ 
+			VertexOnGeom &vog=BTh.VerticesOnGeomVertex[i];
+			if (vog.IsRequiredVertex()){
+				GeomVertex* gv=vog;
+				BamgVertex *bv = vog;
+				_assert_(gv->MeshVertexHook); // use of Geom -> Th
+				VertexOnBThVertex[NbVertexOnBThVertex++]=VertexOnVertex(gv->MeshVertexHook,bv);
+				gv->MeshVertexHook->m = bv->m; // for taking the metric of the background mesh
+			}
+		}
+		_assert_(NbVertexOnBThVertex==NbVerticesOnGeomVertex); /*This might be due to MaxCornerAngle too small*/
+
+		/*STEP 2: reseed boundary edges*/
+
+		//  find the begining of the curve in BTh
+		Gh.UnMarkEdges();	
+		int bfind=0;
+		for (int i=0;i<Gh.nbcurves;i++) bcurve[i]=-1; 
+
+		/*Loop over the backgrounf mesh BTh edges*/
+		for (int iedge=0;iedge<BTh.nbe;iedge++){      
+			Edge &ei = BTh.edges[iedge];
+
+			/*Loop over the 2 vertices of the current edge*/
+			for(int je=0;je<2;je++){
+
+				/* If one of the vertex is required we are in a new curve*/
+				if (ei[je].GeomEdgeHook->IsRequiredVertex()){ 
+
+					/*Get curve number*/
+					int nc=ei.GeomEdgeHook->CurveNumber;
+
+					//_printf_("Dealing with curve number " << nc << "\n");
+					//_printf_("edge on geometry is same as GhCurve? " << (ei.GeomEdgeHook==Gh.curves[nc].FirstEdge || ei.GeomEdgeHook==Gh.curves[nc].LastEdge)?"yes":"no\n");
+					//if(ei.GeomEdgeHook==Gh.curves[nc].FirstEdge || ei.GeomEdgeHook==Gh.curves[nc].LastEdge){
+					//	_printf_("Do we have the right extremity? curve first vertex -> " << ((GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].FirstEdge)[Gh.curves[nc].FirstVertexIndex])?"yes":"no\n");
+					//	_printf_("Do we have the right extremity? curve last  vertex -> " << ((GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].LastEdge)[Gh.curves[nc].LastVertexIndex])?"yes":"no\n");
+					//}
+					//BUG FIX from original bamg
+					/*Check that we are on the same edge and right vertex (0 or 1) */
+					if(ei.GeomEdgeHook==Gh.curves[nc].FirstEdge  && (GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].FirstEdge)[Gh.curves[nc].FirstVertexIndex]){
+						bcurve[nc]=iedge*2+je;
+						bfind++;	
+					}
+					else if ((ei.GeomEdgeHook==Gh.curves[nc].LastEdge  && (GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].LastEdge)[Gh.curves[nc].LastVertexIndex]) && bcurve[nc]==-1){
+						bcurve[nc]=iedge*2+je;
+						bfind++;	
+					}
+				}
+			}
+		} 
+		if (bfind!=Gh.nbcurves){
+			delete [] bcurve;
+			_error_("problem generating number of curves (" << Gh.nbcurves << " found in the geometry but " << bfind << " curve found in the mesh)");
+		}
+
+		// method in 2 + 1 step 
+		//  0.0) compute the length and the number of vertex to do allocation
+		//  1.0) recompute the length
+		//  1.1) compute the  vertex 
+
+		long nbex=0,NbVerticesOnGeomEdgex=0;
+		for (int step=0; step <2;step++){
+
+			long NbOfNewPoints=0;
+			long NbOfNewEdge=0;
+			long iedge;
+			Gh.UnMarkEdges();	
+			double L=0;
+
+			/*Go through all geometrical curve*/
+			for (int icurve=0;icurve<Gh.nbcurves;icurve++){ 
+
+				/*Get edge and vertex (index) of background mesh on this curve*/
+				iedge=bcurve[icurve]/2;
+				int jedge=bcurve[icurve]%2;
+
+				/*Get edge of Bth with index iedge*/
+				Edge &ei = BTh.edges[iedge];
+
+				/*Initialize variables*/
+				double Lstep=0,Lcurve=0;    // step between two points   (phase==1) 
+				long NbCreatePointOnCurve=0;// Nb of new points on curve (phase==1) 
+
+				/*Do phase 0 to step*/
+				for(int phase=0;phase<=step;phase++){
+
+					/*Current curve pointer*/
+					Curve *curve= Gh.curves+icurve;
+
+					/*Get index of current curve*/
+					int icurveequi= Gh.GetId(curve);
+
+					/*For phase 0, check that we are at the begining of the curve only*/
+					if(phase==0 &&  icurveequi!=icurve)  continue;
+
+					int   k0=jedge,k1;
+					Edge* pe=  BTh.edges+iedge;
+					int   iedgeequi=bcurve[icurveequi]/2;
+					int   jedgeequi=bcurve[icurveequi]%2;
+
+					int k0equi=jedgeequi,k1equi;		  
+					Edge * peequi= BTh.edges+iedgeequi;
+					GeomEdge *ongequi = peequi->GeomEdgeHook;
+
+					double sNew=Lstep;// abscisse of the new points (phase==1) 
+					L=0;// length of the curve
+					long i=0;// index of new points on the curve
+					register GeomVertex * GA0 = *(*peequi)[k0equi].GeomEdgeHook;
+					BamgVertex *A0;
+					A0 = GA0->MeshVertexHook;  // the vertex in new mesh
+					BamgVertex *A1;
+					VertexOnGeom *GA1;
+					Edge* PreviousNewEdge = 0;
+
+					// New Curve phase 
+					_assert_(A0-vertices>=0 && A0-vertices<nbv);
+					if(ongequi->Required()){
+						GeomVertex *GA1 = *(*peequi)[1-k0equi].GeomEdgeHook;
+						A1 = GA1->MeshVertexHook;  //
+					}       
+					else {
+						for(;;){
+							Edge &ee=*pe; 
+							Edge &eeequi=*peequi; 
+							k1 = 1-k0; // next vertex of the edge 
+							k1equi= 1 - k0equi;
+							_assert_(pe && ee.GeomEdgeHook);
+							ee.GeomEdgeHook->SetMark();
+							BamgVertex & v0=ee[0], & v1=ee[1];
+							R2 AB=(R2)v1-(R2)v0;
+							double L0=L,LAB;
+							LAB=LengthInterpole(v0.m,v1.m,AB);
+							L+= LAB;
+
+							if (phase){
+								// computation of the new points for the given curve
+								while ((i!=NbCreatePointOnCurve) && sNew<=L) { 
+
+									//some checks
+									_assert_(sNew>=L0);
+									_assert_(LAB);
+									_assert_(vertices && nbv<maxnbv);
+									_assert_(edges && nbe<nbex);
+									_assert_(VerticesOnGeomEdge && NbVerticesOnGeomEdge<NbVerticesOnGeomEdgex);
+
+									// new vertex on edge
+									A1=vertices+nbv++;
+									GA1=VerticesOnGeomEdge+NbVerticesOnGeomEdge;
+									Edge* e = edges + nbe++;
+									double se= (sNew-L0)/LAB;
+									if (se<0 || se>=1.000000001){
+										_error_("Problem creating point on a boundary: se=" << se << " should be in [0 1]");
+									}
+									se = abscisseInterpole(v0.m,v1.m,AB,se,1);
+									if (se<0 || se>1){
+										_error_("Problem creating point on a boundary: se=" << se << " should be in [0 1]");
+									}
+									se = k1         ? se : 1. - se;
+									se = k1==k1equi ? se : 1. - se;
+									VertexOnBThEdge[NbVerticesOnGeomEdge++] = VertexOnEdge(A1,&eeequi,se); // save 
+									ongequi=Gh.ProjectOnCurve(eeequi,se,*A1,*GA1); 
+									A1->ReferenceNumber = eeequi.ReferenceNumber;
+									A1->DirOfSearch =NoDirOfSearch;
+									e->GeomEdgeHook = ongequi;
+									e->v[0]=A0;
+									e->v[1]=A1;
+									e->ReferenceNumber = eeequi.ReferenceNumber;
+									e->adj[0]=PreviousNewEdge;
+
+									if (PreviousNewEdge) PreviousNewEdge->adj[1]=e;
+									PreviousNewEdge=e;
+									A0=A1;
+									sNew += Lstep;
+									if (++i== NbCreatePointOnCurve) break;
+								}
+							}
+
+							//some checks
+							_assert_(ee.GeomEdgeHook->CurveNumber==ei.GeomEdgeHook->CurveNumber);
+							if (ee[k1].GeomEdgeHook->IsRequiredVertex()) {
+								_assert_(eeequi[k1equi].GeomEdgeHook->IsRequiredVertex());
+								register GeomVertex * GA1 = *eeequi[k1equi].GeomEdgeHook;
+								A1=GA1->MeshVertexHook;// the vertex in new mesh
+								_assert_(A1-vertices>=0 && A1-vertices<nbv);
+								break;
+							}
+							if (!ee.adj[k1]) {
+								_error_("adj edge " << BTh.GetId(ee) << ", nbe=" << nbe << ", Gh.vertices=" << Gh.vertices);
+							}
+							pe = ee.adj[k1]; // next edge
+							k0 = pe->Intersection(ee); 
+							peequi= eeequi.adj[k1equi];  // next edge
+							k0equi=peequi->Intersection(eeequi);            
+						}// for(;;) end of the curve
+					}
+
+					if (phase){ // construction of the last edge
+						Edge* e=edges + nbe++;
+						e->GeomEdgeHook  = ongequi;
+						e->v[0]=A0;
+						e->v[1]=A1;
+						e->ReferenceNumber = peequi->ReferenceNumber;
+						e->adj[0]=PreviousNewEdge;
+						e->adj[1]=0;
+						if (PreviousNewEdge) PreviousNewEdge->adj[1]=e;
+						PreviousNewEdge = e;
+
+						_assert_(i==NbCreatePointOnCurve);
+					}
+
+					if (!phase)  { // 
+						long NbSegOnCurve = Max((long)(L+0.5),(long) 1);// nb of seg
+						Lstep = L/NbSegOnCurve; 
+						Lcurve = L;
+						NbCreatePointOnCurve = NbSegOnCurve-1;
+						NbOfNewEdge += NbSegOnCurve;
+						NbOfNewPoints += NbCreatePointOnCurve;
+					}
+				}
+			}//  end of curve loop 
+
+			//Allocate memory
+			if(step==0){
+				if(nbv+NbOfNewPoints > maxnbv) {
+					_error_("too many vertices on geometry: " << nbv+NbOfNewPoints << " >= " << maxnbv);
+				}
+				edges = new Edge[NbOfNewEdge];
+				nbex = NbOfNewEdge;
+				if(NbOfNewPoints) {
+					VerticesOnGeomEdge    = new VertexOnGeom[NbOfNewPoints];
+					NbVertexOnBThEdge     = NbOfNewPoints;
+					VertexOnBThEdge       = new  VertexOnEdge[NbOfNewPoints];
+					NbVerticesOnGeomEdgex = NbOfNewPoints;
+				}
+				NbOfNewPoints =0;
+				NbOfNewEdge = 0;
+			}
+		}
+		_assert_(nbe!=0);
+		delete [] bcurve;
+
+		//Insert points inside existing triangles
+		if (verbose>4) _printf_("      -- current number of vertices = " << nbv << "\n");
+		if (verbose>3) _printf_("      Creating initial Constrained Delaunay Triangulation...\n");
+		if (verbose>3) _printf_("         Inserting boundary points\n");
+		Insert();
+
+		//Force the boundary
+		if (verbose>3) _printf_("         Forcing boundaries\n");
+		ForceBoundary();
+
+		//Extract SubDomains
+		if (verbose>3) _printf_("         Extracting subdomains\n");
+		FindSubDomain();
+
+		if (verbose>3) _printf_("      Inserting internal points\n");
+		NewPoints(BTh,bamgopts,KeepVertices) ;
+		if (verbose>4) _printf_("      -- current number of vertices = " << nbv << "\n");
+	}
+	/*}}}*/
+
+	/*Intermediary*/
+	/*FUNCTION CloseBoundaryEdge{{{*/
+	AdjacentTriangle CloseBoundaryEdge(I2 A,Triangle *t, double &a,double &b) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/CloseBoundaryEdge)*/
+
+		int k=(*t)(0) ?  ((  (*t)(1) ? ( (*t)(2) ? -1 : 2) : 1  )) : 0;
+		int dir=0;
+		if (k<0){
+			_error_("k<0");
+		}
+		int kkk=0;  
+		Icoor2 IJ_IA,IJ_AJ;
+		AdjacentTriangle edge(t,OppositeEdge[k]);          
+		for (;;edge = dir >0 ? Next(Adj(Next(edge))) : Previous(Adj(Previous(edge)))) {  
+			kkk++;
+			if (kkk>=1000){
+				_error_("kkk>=1000");
+			}
+			BamgVertex  &vI =  *edge.EdgeVertex(0);
+			BamgVertex  &vJ =  *edge.EdgeVertex(1);
+			I2 I=vI, J=vJ, IJ= J-I;
+			IJ_IA = (IJ ,(A-I));
+			if (IJ_IA<0) {
+				if (dir>0) {a=1;b=0;return edge;}// change of signe => I
+				else {dir=-1;
+					continue;}};// go in direction i 
+					IJ_AJ = (IJ ,(J-A));
+					if (IJ_AJ<0) {
+						if(dir<0)  {a=0;b=1;return edge;}            
+						else {dir = 1;
+							continue;}}// go in direction j
+							double IJ2 = IJ_IA + IJ_AJ;
+							if (IJ2==0){
+								_error_("IJ2==0");
+							}
+							a= IJ_AJ/IJ2;
+							b= IJ_IA/IJ2;
+							return edge;
+		  } 
+	}
+	/*}}}*/
+/*FUNCTION ForceEdge{{{*/
+int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret)  { 
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceEdge)*/
+
+	int NbSwap =0;
+	if (!a.t || !b.t){ // the 2 vertex is in a mesh
+		_error_("!a.t || !b.t");
+	}
+	int k=0;
+	taret=AdjacentTriangle(0,0); // erreur 
+
+	AdjacentTriangle tta(a.t,EdgesVertexTriangle[a.IndexInTriangle][0]);
+	BamgVertex   *v1, *v2 = tta.EdgeVertex(0),*vbegin =v2;
+	// we turn around a in the  direct direction  
+
+	Icoor2 det2 = v2 ? det(*v2,a,b): -1 , det1;
+	if(v2) // normal case 
+	 det2 = det(*v2,a,b);
+	else { // no chance infini vertex try the next
+		tta= Previous(Adj(tta));
+		v2 = tta.EdgeVertex(0);
+		vbegin =v2;
+		if (!v2){
+			_error_("!v2");
+		}
+		det2 = det(*v2,a,b);
+	}
+
+	while (v2 != &b) {
+		AdjacentTriangle tc = Previous(Adj(tta));    
+		v1 = v2; 
+		v2 = tc.EdgeVertex(0);
+		det1 = det2;
+		det2 =  v2 ? det(*v2,a,b): det2; 
+
+		if((det1 < 0) && (det2 >0)) { 
+			// try to force the edge 
+			BamgVertex * va = &a, *vb = &b;
+			tc = Previous(tc);
+			if (!v1 || !v2){
+				_error_("!v1 || !v2");
+			}
+			Icoor2 detss = 0,l=0,ks;
+			while ((ks=SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
+			 if(l++ > 10000000) {
+				 _error_("Loop in forcing Egde, nb de swap=" << NbSwap << ", nb of try swap (" << l << ") too big");
+			 }
+			BamgVertex *aa = tc.EdgeVertex(0), *bb = tc.EdgeVertex(1);
+			if (( aa == &a ) && (bb == &b) ||  (bb ==  &a ) && (aa == &b)) {
+				tc.SetLock();
+				a.Optim(1,0);
+				b.Optim(1,0);
+				taret = tc;
+				return NbSwap;
+			}
+			else 
+			  {
+				taret = tc;
+				return -2; // error  boundary is crossing
+			  }
+		}
+		tta = tc;
+		k++;
+		if (k>=2000){
+			_error_("k>=2000");
+		}
+		if ( vbegin == v2 ) return -1;// error 
+	}
+
+	tta.SetLock();
+	taret=tta;
+	a.Optim(1,0);
+	b.Optim(1,0);
+	return NbSwap; 
+}
+/*}}}*/
+/*FUNCTION swap{{{*/
+void  swap(Triangle *t1,short a1, Triangle *t2,short a2, BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2){ 
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
+	// --------------------------------------------------------------
+	// short a2=aa[a];// les 2 numero de l arete dans les 2 triangles
+	//                               
+	//               sb                     sb    
+	//             / | \                   /   \                      !
+	//         as1/  |  \                 /a2   \                     !
+	//           /   |   \               /    t2 \                    !
+	//       s1 /t1  | t2 \s2  -->   s1 /___as2___\s2                 !
+	//          \  a1|a2  /             \   as1   /  
+	//           \   |   /               \ t1    /   
+	//            \  |  / as2             \   a1/    
+	//             \ | /                   \   /     
+	//              sa                       sa   
+	//  -------------------------------------------------------------
+	int as1 = NextEdge[a1];
+	int as2 = NextEdge[a2];
+	int ap1 = PreviousEdge[a1];
+	int ap2 = PreviousEdge[a2];
+	(*t1)(VerticesOfTriangularEdge[a1][1]) = s2 ; // avant sb
+	(*t2)(VerticesOfTriangularEdge[a2][1]) = s1  ; // avant sa
+	// mise a jour des 2 adjacences externes 
+	AdjacentTriangle taas1 = t1->Adj(as1),
+						  taas2 = t2->Adj(as2),
+						  tas1(t1,as1), tas2(t2,as2),
+						  ta1(t1,a1),ta2(t2,a2);
+	// externe haut gauche
+	taas1.SetAdj2(ta2, taas1.GetAllFlag_UnSwap());
+	// externe bas droite
+	taas2.SetAdj2(ta1, taas2.GetAllFlag_UnSwap());
+	// remove the Mark  UnMarkSwap 
+	t1->SetUnMarkUnSwap(ap1);
+	t2->SetUnMarkUnSwap(ap2);
+	// interne 
+	tas1.SetAdj2(tas2);
+
+	t1->det = det1;
+	t2->det = det2;
+
+	t1->SetSingleVertexToTriangleConnectivity();
+	t2->SetSingleVertexToTriangleConnectivity();
+} // end swap 
+/*}}}*/
+	/*FUNCTION SwapForForcingEdge{{{*/
+	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,AdjacentTriangle & tt1,Icoor2 & dets1, Icoor2 & detsa,Icoor2 & detsb, int & NbSwap) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SwapForForcingEdge)*/
+		// l'arete ta coupe l'arete pva pvb
+		// de cas apres le swap sa coupe toujours
+		// on cherche l'arete suivante 
+		// on suppose que detsa >0 et detsb <0
+		// attention la routine echange pva et pvb 
+
+		if(tt1.Locked()) return 0; // frontiere croise 
+
+		AdjacentTriangle tt2 = Adj(tt1);
+		Triangle *t1=tt1,*t2=tt2;// les 2 triangles adjacent
+		short a1=tt1,a2=tt2;// les 2 numero de l arete dans les 2 triangles
+		if ( a1<0 || a1>=3 ){
+			_error_("a1<0 || a1>=3");
+		}
+
+		BamgVertex & sa= (* t1)[VerticesOfTriangularEdge[a1][0]];
+		BamgVertex & s1= (*t1)[OppositeVertex[a1]];
+		BamgVertex & s2= (*t2)[OppositeVertex[a2]];
+
+		Icoor2 dets2 = det(*pva,*pvb,s2);
+		Icoor2 det1=t1->det , det2=t2->det ;
+		Icoor2 detT = det1+det2;
+		if ((det1<=0 ) || (det2<=0)){
+			_error_("(det1<=0 ) || (det2<=0)");
+		}
+		if ( (detsa>=0) || (detsb<=0) ){ // [a,b] cut infinite line va,bb
+			_error_("(detsa>=0) || (detsb<=0)");
+		}
+		Icoor2 ndet1 = bamg::det(s1,sa,s2);
+		Icoor2 ndet2 = detT - ndet1;
+
+		int ToSwap =0; //pas de swap
+		if ((ndet1 >0) && (ndet2 >0)) 
+		  { // on peut swaper  
+			if ((dets1 <=0 && dets2 <=0) || (dets2 >=0 && detsb >=0))
+			 ToSwap =1; 
+			else // swap alleatoire 
+			 if (BinaryRand()) 
+			  ToSwap =2; 
+		  }
+		if (ToSwap) NbSwap++,
+		 bamg::swap(t1,a1,t2,a2,&s1,&s2,ndet1,ndet2);
+
+		int ret=1;
+
+		if (dets2 < 0) {// haut
+			dets1 = ToSwap ? dets1 : detsa ;
+			detsa = dets2; 
+			tt1 =  Previous(tt2) ;}
+		else if (dets2 > 0){// bas 
+			dets1 = ToSwap ? dets1 : detsb ;
+			detsb = dets2;
+			//xxxx tt1 = ToSwap ? tt1 : Next(tt2);
+			if(!ToSwap) tt1 =  Next(tt2);
+		}
+		else { // changement de direction 
+			ret = -1;
+			Exchange(pva,pvb);
+			Exchange(detsa,detsb);
+			Exchange(dets1,dets2);
+			Exchange(tt1,tt2);
+			dets1=-dets1;
+			dets2=-dets2;
+			detsa=-detsa;
+			detsb=-detsb;
+
+			if (ToSwap) 
+			 if (dets2 < 0) {// haut
+				 dets1 = (ToSwap ? dets1 : detsa) ;
+				 detsa = dets2; 
+				 tt1 =  Previous(tt2) ;}
+			 else if (dets2 > 0){// bas 
+				 dets1 = (ToSwap ? dets1 : detsb) ;
+				 detsb =  dets2;
+				 if(!ToSwap) tt1 =  Next(tt2);
+			 }
+			 else {// on a fin ???
+				 tt1 = Next(tt2);
+				 ret =0;}
+
+		}
+		return ret;
+	}
+	/*}}}*/
+
+}
Index: /issm/trunk/src/c/bamg/Mesh.h
===================================================================
--- /issm/trunk/src/c/bamg/Mesh.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/Mesh.h	(revision 15396)
@@ -0,0 +1,192 @@
+#ifndef _MESH_H_
+#define _MESH_H_
+
+#include "./include.h"
+#include "./BamgOpts.h"
+#include "./BamgMesh.h"
+#include "./BamgGeom.h"
+#include "./Triangle.h"
+#include "./VertexOnGeom.h"
+#include "./VertexOnVertex.h"
+#include "./VertexOnEdge.h"
+#include "./ListofIntersectionTriangles.h"
+
+namespace bamg {
+
+	class Geometry;
+	class CrackedEdge;
+	class BamgQuadtree;
+	class SubDomain;
+
+	class Mesh {
+
+		public:
+
+			Geometry                    & Gh;                    // Geometry
+			Mesh                        & BTh;                   // Background Mesh Bth== *this =>no background
+			BamgVertex                   *vertices;
+			Triangle                     *triangles;
+			Edge                         *edges;
+			BamgQuadtree                 *quadtree;
+			BamgVertex                  **orderedvertices;
+			SubDomain                    *subdomains;
+			long                          NbRef;                 // counter of ref on the this class if 0 we can delete
+			long                          maxnbv,maxnbt;         // nombre max de sommets , de triangles
+			long                          nbv,nbt,nbe,nbq;       // nb of vertices, of triangles, of edges and quadrilaterals
+			long                          nbsubdomains;
+			long                          nbtout;                // Nb of oudeside triangle
+
+			R2                            pmin,pmax;             // extrema
+			double                        coefIcoor;             // coef to integer Icoor1;
+			ListofIntersectionTriangles   lIntTria;
+
+			long                          NbVerticesOnGeomVertex;
+			VertexOnGeom                 *VerticesOnGeomVertex;
+			long                          NbVerticesOnGeomEdge;
+			VertexOnGeom                 *VerticesOnGeomEdge;
+			long                          NbVertexOnBThVertex;
+			VertexOnVertex               *VertexOnBThVertex;
+			long                          NbVertexOnBThEdge;
+			VertexOnEdge                 *VertexOnBThEdge;
+			long                          NbCrackedVertices;
+			long                         *CrackedVertices;
+			long                          NbCrackedEdges;
+			CrackedEdge                  *CrackedEdges;
+
+			//Constructors/Destructors
+			Mesh(BamgGeom* bamggeom,BamgMesh* bamgmesh,BamgOpts* bamgopts);
+			Mesh(int* index,double* x,double* y,int nods,int nels);/*MeshConvert*/
+			Mesh(double* x,double* y,int nods); /*BamgTriangulate*/
+			Mesh(Mesh &,Geometry * pGh=0,Mesh* pBTh=0,long maxnbv_in=0 ); //copy operator
+			Mesh(const Mesh &,const int *flag,const int *bb,BamgOpts* bamgopts); // truncature
+			Mesh(long maxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices=1);
+			Mesh(long maxnbv,Geometry & G,BamgOpts* bamgopts);
+			~Mesh(); 
+
+			//Operators
+			const BamgVertex &operator[](long i) const { return vertices[i];  };
+			BamgVertex       &operator[](long i) { return vertices[i];        };
+			const Triangle   &operator()(long i) const { return triangles[i]; };
+			Triangle         &operator()(long  i) { return triangles[i];             };
+
+			//Methods
+			void SetIntCoor(const char * from =0);
+			double MinimalHmin();
+			double MaximalHmax();
+			I2 R2ToI2(const R2 & P) const;
+			R2 I2ToR2(const I2 & P) const;
+			void AddVertex(BamgVertex & s,Triangle * t,Icoor2 *  =0) ;
+			void Insert();
+			void Echo(void);
+			void ForceBoundary();
+			void FindSubDomain(int OutSide=0);
+			long TriangleReferenceList(long*) const;
+			void TriangleIntNumbering(long* renumbering);
+			void ShowHistogram() const;
+			void CrackMesh(BamgOpts* bamgopts);
+			void ShowRegulaty() const;
+			void SmoothMetric(double raisonmax) ;
+			void BoundAnisotropy(double anisomax,double hminaniso= 1e-100) ;
+			void MaxSubDivision(double maxsubdiv);
+			Edge** MakeGeomEdgeToEdge();
+			long SplitInternalEdgeWithBorderVertices();
+			void MakeQuadrangles(double costheta);
+			int  SplitElement(int choice);
+			void MakeBamgQuadtree();
+			void NewPoints(Mesh &,BamgOpts* bamgopts,int KeepVertices=1);
+			long InsertNewPoints(long nbvold,long & NbTSwap) ; 
+			void TrianglesRenumberBySubDomain(bool justcompress=false);
+			void VerticesRenumber(long * renu);
+			void SmoothingVertex(int =3,double=0.3);
+			Metric MetricAt (const R2 &) const;
+			GeomEdge* ProjectOnCurve( Edge & AB, BamgVertex &  A, BamgVertex & B,double theta, BamgVertex & R,VertexOnEdge & BR,VertexOnGeom & GR);
+			long GetId(const Triangle & t) const;
+			long GetId(const Triangle * t) const;
+			long GetId(const BamgVertex & t) const;
+			long GetId(const BamgVertex * t) const;
+			long GetId(const Edge & t) const;
+			long GetId(const Edge * t) const;
+			BamgVertex* NearestVertex(Icoor1 i,Icoor1 j) ;
+			Triangle* TriangleFindFromCoord(const I2 & ,Icoor2 [3],Triangle *tstart=0) const;
+			void ReadMesh(int* index,double* x,double* y,int nods,int nels);
+			void ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts);
+			void WriteMesh(BamgMesh* bamgmesh,BamgOpts* bamgopts);
+			void ReadMetric(const BamgOpts* bamgopts);
+			void WriteMetric(BamgOpts* bamgopts);
+			void WriteIndex(int** pindex,int* pnels);
+			void AddMetric(BamgOpts* bamgopts);
+			void BuildMetric0(BamgOpts* bamgopts);
+			void BuildMetric1(BamgOpts* bamgopts);
+			void AddGeometryMetric(BamgOpts* bamgopts);
+			int  isCracked() const;
+			void BuildGeometryFromMesh(BamgOpts* bamgopts=NULL);
+			void ReconstructExistingMesh();
+
+			//Inline methods
+			inline  void CreateSingleVertexToTriangleConnectivity(){
+				for (int i=0;i<nbv;i++) vertices[i].IndexInTriangle=0, vertices[i].t=NULL;
+				for (int i=0;i<nbt;i++) triangles[i].SetSingleVertexToTriangleConnectivity();
+			}
+			inline  void  UnMarkUnSwapTriangle(){
+				for (int i=0;i<nbt;i++)
+				 for(int j=0;j<3;j++)
+				  triangles[i].SetUnMarkUnSwap(j);
+			  }
+			inline  void  SetVertexFieldOn(){
+				for (int i=0;i<nbv;i++)                    vertices[i].GeomEdgeHook=NULL;
+				for (int j=0;j<NbVerticesOnGeomVertex;j++) VerticesOnGeomVertex[j].SetOn();
+				for (int k=0;k<NbVerticesOnGeomEdge;k++ )  VerticesOnGeomEdge[k].SetOn();
+			}	       
+			inline  void   SetVertexFieldOnBTh(){
+				for (int i=0;i<nbv;i++)                 vertices[i].GeomEdgeHook=NULL;
+				for (int j=0;j<NbVertexOnBThVertex;j++) VertexOnBThVertex[j].SetOnBTh();
+				for (int k=0;k<NbVertexOnBThEdge;k++ )  VertexOnBThEdge[k].SetOnBTh();
+			}
+
+		private:
+			void TriangulateFromGeom1(BamgOpts* bamgopts,int KeepVertices=1);// the real constructor mesh adaption
+			void TriangulateFromGeom0(BamgOpts* bamgopts);// the real constructor mesh generator
+			void Triangulate(double* x,double* y,int nods);
+			void Init(long);
+	};
+
+	/*Intermediary*/
+	AdjacentTriangle CloseBoundaryEdge(I2 ,Triangle *, double &,double &) ;
+	void  swap(Triangle *t1,short a1,
+				Triangle *t2,short a2,
+				BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2);
+	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,
+				AdjacentTriangle & tt1,Icoor2 & dets1,
+				Icoor2 & detsa,Icoor2 & detsb, int & nbswap);
+	int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret) ;
+	inline AdjacentTriangle Previous(const AdjacentTriangle & ta){
+		return AdjacentTriangle(ta.t,PreviousEdge[ta.a]);
+	}
+	inline AdjacentTriangle Next(const AdjacentTriangle & ta){
+		return AdjacentTriangle(ta.t,NextEdge[ta.a]);
+	}
+	inline  AdjacentTriangle Adj(const AdjacentTriangle & a){
+		return  a.Adj();
+	}
+	inline void Adj(GeomEdge * & on,int &i){
+		int j=i;i=on->AdjVertexIndex[i];on=on->Adj[j];
+	}
+	inline double qualite(const BamgVertex &va,const BamgVertex &vb,const BamgVertex &vc){
+		double ret; 
+		I2 ia=va,ib=vb,ic=vc;
+		I2 ab=ib-ia,bc=ic-ib,ac=ic-ia;
+		Icoor2 deta=Det(ab,ac);
+		if (deta <=0) ret = -1;
+		else {
+			double a = sqrt((double) (ac,ac)),
+					 b = sqrt((double) (bc,bc)),
+					 c = sqrt((double) (ab,ab)),
+					 p = a+b+c;
+			double h= Max(Max(a,b),c),ro=deta/p;
+			ret = ro/h;
+		}
+		return ret;
+	}
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/Metric.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Metric.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/Metric.cpp	(revision 15396)
@@ -0,0 +1,352 @@
+#include <cstdio>
+#include <string.h>
+#include <cmath>
+
+#include "Metric.h"
+#include "../shared/shared.h"
+
+using namespace std;
+
+namespace bamg {
+
+	SaveMetricInterpole  LastMetricInterpole;
+
+	/*Constructor/Destructor*/
+	/*FUNCTION Metric::Metric(double a){{{*/
+	Metric::Metric(double a): a11(1/(a*a)),a21(0),a22(1/(a*a)){
+
+	}/*}}}*/
+	/*FUNCTION Metric::Metric(double a,double b,double c){{{*/
+	Metric::Metric(double a,double b,double c) :a11(a),a21(b),a22(c){
+
+	}/*}}}*/
+	/*FUNCTION Metric::Metric(const double  a[3],const  Metric& m0, const  Metric& m1,const  Metric&  m2 ){{{*/ 
+	Metric::Metric(const double  a[3],const  Metric& m0, const  Metric& m1,const  Metric& m2 ){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/Metric)*/
+
+		Metric mab(a[0]*m0.a11 + a[1]*m1.a11 + a[2]*m2.a11,
+					a[0]*m0.a21 + a[1]*m1.a21 + a[2]*m2.a21,
+					a[0]*m0.a22 + a[1]*m1.a22 + a[2]*m2.a22);
+
+		EigenMetric vab(mab);
+
+		R2 v1(vab.v.x,vab.v.y);
+		R2 v2(-v1.y,v1.x);
+
+		double h1 = a[0] / m0(v1) + a[1] / m1(v1) + a[2] / m2(v1);
+		double h2 = a[0] / m0(v2) + a[1] / m1(v2) + a[2] / m2(v2);
+
+		vab.lambda1 =  1 / (h1*h1);
+		vab.lambda2 =  1 / (h2*h2);
+		*this = vab;
+	}
+	/*}}}*/
+	/*FUNCTION Metric::Metric(double  a,const  Metric& ma, double  b,const  Metric& mb){{{*/
+	Metric::Metric(double  a,const  Metric& ma, double  b,const  Metric& mb) { 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/EigenMetric)*/
+
+		/*Compute metric (linear combination of ma and mb)*/
+		Metric mab(a*ma.a11+b*mb.a11,a*ma.a21+b*mb.a21,a*ma.a22+b*mb.a22);
+
+		/*Get Eigen values and vectors*/
+		EigenMetric vab(mab);
+		R2 v1(vab.v.x,vab.v.y);
+		R2 v2(-v1.y,v1.x);
+
+		/*Modify eigen values (a+b=1)*/
+		double h1 = a/ma(v1) + b/mb(v1);
+		double h2 = a/ma(v2) + b/mb(v2);
+		vab.lambda1 =  1/(h1*h1);
+		vab.lambda2 =  1/(h2*h2);
+		*this=vab;
+	}
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Metric::det{{{*/
+	double Metric::det() const {
+		return a11*a22-a21*a21;
+	}  /*}}}*/
+	/*FUNCTION Metric::Echo {{{*/
+	void Metric::Echo(void){
+
+		_printf_("Metric:\n");
+		_printf_("   [a11 a21 a22]: [" << a11 << " " << a21 << " " << a22 << "]\n");
+
+		return;
+	}
+	/*}}}*/
+	/*FUNCTION Metric::IntersectWith{{{*/
+	int Metric::IntersectWith(const Metric& M2) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectWith)*/
+
+		/*Get a new metric from an existing metric (M1=this)
+		 * and a new metric given in input M2 using a 
+		 * Simultaneous Matrix Reduction:
+		 * If M1 and M2 are 2 metrics, we must build N=M1^-1 M2 (Alauzet2003 p16) 
+		 * the eigen vectors of N form a matrix P
+		 * The new metric M = M1 inter M2 is then given by:
+		 *
+		 *      -T [ max(lambda1, mu1)          0         ]  -1				 
+		 * M = P   [                                      ] P		 
+		 *         [        0            max(lambda2, mu2)] 
+		 *
+		 * where lambdai and mui can be computed using Rayleigh formula: 
+		 *    lambdai = vi' M1 vi
+		 * with vi eigen vectors of N (columns of P)
+		 */
+
+		int         change=0;
+		Metric &M1=*this;
+		D2xD2       P;
+
+		//Get P, eigen vectors of N=inv(M1) M2
+		SimultaneousMatrixReduction(*this,M2,P);
+
+		//extract the eigen vectors of P (columns)
+		R2 v1(P.x.x,P.y.x);
+		R2 v2(P.x.y,P.y.y);
+
+		//compute lambdai mui
+		double lambda1=M1(v1,v1);
+		double lambda2=M1(v2,v2);
+		double mu1=M2(v1,v1);
+		double mu2=M2(v2,v2);
+
+		//check where any change needs to be done on M1
+		if ( lambda1 < mu1 )  change=1,lambda1=mu1;
+		if ( lambda2 < mu2 )  change=1,lambda2=mu2; 
+
+		//update M1 if necessary
+		if (change) {
+			D2xD2 invP(P.inv());
+			D2xD2 D(lambda1,0,0,lambda2); 
+			D2xD2 M(invP.t()*D*invP);
+			a11=M.x.x;
+			a21=0.5*(M.x.y+M.y.x);
+			a22=M.y.y;
+		}
+		return change;
+	}
+	/*}}}*/
+	/*FUNCTION Metric::mul{{{*/
+	R2     Metric::mul(const R2 x)const {
+		return R2(a11*x.x+a21*x.y,a21*x.x+a22*x.y);
+	}/*}}}*/
+
+	/*Intermediary*/
+	/*FUNCTION LengthInterpole{{{*/
+	double LengthInterpole(const Metric& Ma,const  Metric& Mb, R2 AB) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/LengthInterpole)*/
+
+		double k=1./2.;
+		int level=0;
+		static int kkk=0;
+		static  Metric Ms1[32],Ms2[32];
+		static double lMs1[32],lMs2[32];
+		static double K[32];
+		double l=0,sss=0;
+		Ms1[level]=Ma;
+		Ms2[level]=Mb;
+		double sa =  Ma(AB);
+		double sb =  Mb(AB);
+		lMs1[level]=sa;
+		lMs2[level]=sb;
+		K[level]=k;
+		level++;
+		int i=0;
+		double * L= LastMetricInterpole.L, *S = LastMetricInterpole.S;
+		double  sstop = 0.1; // Max(0.6,(sa+sb)/5000);
+		while (level) {
+			level--;
+			Metric M1=Ms1[level];
+			Metric M2=Ms2[level];
+			k=K[level];
+			double s1=  lMs1[level];
+			double s2=  lMs2[level];
+
+			double s= (s1+s2)*k;
+			if( s > sstop   && level < 30 && i < 500-level ) {
+				Metric Mi(0.5,M1,0.5,M2);
+				double si = Mi(AB);
+				if( Abs((s1+s2)-(si+si)) > s1*0.001) 
+				  {
+					k=k/2;
+					// we begin by the end to walk in the correct direction from a to b
+					// due to the stack 
+					Ms1[level]=Mi;
+					Ms2[level]=M2;
+					lMs1[level]=si;
+					lMs2[level]=s2;
+					K[level]=k;
+					level++;
+					Ms1[level]=M1;
+					Ms2[level]=Mi;
+					lMs1[level]=s1;
+					lMs2[level]=si;
+					K[level]=k;
+					level++;
+				  }
+				else
+				 L[i]= l += s,S[i]=sss+=k,i++;
+			}
+			else 
+			 L[i]= l += s,S[i]=sss+=k,i++;
+		}
+		// warning for optimisation S is in [0:0.5] not in [0:1]
+		if (i>=512){
+			_error_("i>=512");
+		}
+		LastMetricInterpole.lab=l;
+		LastMetricInterpole.opt=i;
+		if (i>200 && kkk++<10) _printf_("WARNING: LengthInterpole: ( i=" << i << " l=" << l << " sss=" << sss << " ) " << sstop << "\n"); 
+		return l;
+	}
+	/*}}}*/
+	/*FUNCTION SimultaneousMatrixReduction{{{*/
+	void SimultaneousMatrixReduction( Metric M1,  Metric M2, D2xD2 &V) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/ReductionSimultanee)*/
+
+		/*In this routine we must return a matrix V that is composed of the 
+		 * eigen vectors of N=inv(M1) M2.
+		 * Instead of looking at N directly, we are going to use the fact that
+		 * M1 and M2 are symmetrical, positive definite. 
+		 * The eigen values of N are given by solving
+		 *    inv(M1) M2 V = lambda V
+		 * which is equivalent to
+		 *    M2 V = lambda M1 V
+		 * and we will hence solve
+		 *    (M2 - lambda M1) V = 0
+		 */
+
+		//M1 and M2 components
+		double a11=M1.a11,a21=M1.a21,a22=M1.a22;
+		double b11=M2.a11,b21=M2.a21,b22=M2.a22;
+
+		/*To get the eigen values, we solve the following problem:
+		 *    det(M2-lambda M1) = 0
+		 *    (b11 - lambda a11)(b22-lambda a22) - (b21-lambda a21)^2
+		 * and we have the following trinome:
+		 *    a lambda^2 + b lambda + c =0
+		 * with:
+		 *    a = a11 a22 - a21 a21 (=det(M1))
+		 *    b = -a11 b22 -b11 a22 + 2 b21 a21
+		 *    c = b11 b22 - b21 b21 (=det(M2))
+		 *    */
+		const double a= a11*a22  - a21*a21;
+		const double b=-a11*b22 - b11*a22+2*b21*a21;
+		const double c=-b21*b21 + b11*b22;
+		const double bb=b*b,ac=a*c;
+		const double delta= bb-4*ac;
+
+		// first, case of a double root if:
+		//  - all the terms are very small (a??)
+		//  - or : delta is very small
+		if ( (bb + Abs(ac) < 1.0e-34 ) ||  (delta < 1.0e-6*bb) ){
+			//all vectors are eigen vectors -> choose 1,0 and 0,1
+			V= D2xD2(1,0,0,1);
+		}
+
+		//general case: two distinct roots: lambda1 and lambda2
+		else {
+
+			/*Compute eigen values*/
+			const double delta2 = sqrt(delta);
+			double lambda[2];
+			lambda[0]= (-b - delta2)/(2*a);
+			lambda[1]= (-b + delta2)/(2*a);
+
+			/*compute eigen vectors*/
+			double vp[2][2];
+			double v0,v1,v2;
+			double s0,s1;
+
+			for(int i=0;i<2;i++){
+				/*Now, one must find the eigen vectors. For that we use the 
+				 * following property of the inner product
+				 *    (Ax,b) = transp(b) Ax = transp(x) transp(A) b
+				 *           = (transp(A) b ,x)
+				 * Here we are dealing with A= M2 - lambda M1 which is symmetrical:
+				 *    for all (x,y) in R2 
+				 *       ((M2 - lambda M1)x,y)=((M2 - lambda M1)y,x)
+				 * If y is in Ker(M2 - lambda M1):
+				 *    for all x in R2
+				 *       ((M2 - lambda M1)y,x)=0
+				 * This shows that:
+				 *    Ker(M2 - lambda M1) is orthogonal to Im(M2 - lambda M1)
+				 * To find the eigen vectors, we only have to find two vectors
+				 * of the image and take their perpendicular as long as they are
+				 * not 0.
+				 * To do that, we take (1,0) and (0,1) and take the larger norm*/
+
+				//compute V = M2 - lambdai M1
+				v0 = b11 - lambda[i]*a11;
+				v1 = b21 - lambda[i]*a21;
+				v2 = b22 - lambda[i]*a22;
+
+				// compute s1=norm(V(1,0)) and s0=norm(V(0,1))
+				s0 = v0*v0 + v1*v1;
+				s1 = v1*v1 + v2*v2;
+
+				//compute vp1 = (vp1x,vp1y)
+				if(s1 < s0){
+					s0=sqrt(s0);
+					vp[0][i]=   v1/s0;
+					vp[1][i]= - v0/s0;
+				}
+				else{
+					s1=sqrt(s1);
+					vp[0][i]=   v2/s1;
+					vp[1][i]= - v1/s1;
+				}
+			}
+
+			//compute V from vp
+			V=D2xD2(vp[0][0],vp[0][1],vp[1][0],vp[1][1]);
+		}
+	}
+	/*}}}*/
+	/*FUNCTION abscisseInterpole{{{*/
+	double abscisseInterpole(const Metric& Ma,const  Metric& Mb, R2 AB,double s,int optim) { 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/abscisseInterpole)*/
+
+		if(!optim)  LengthInterpole(Ma,Mb,AB);
+		double l  = s* LastMetricInterpole.lab,r;
+		int j=LastMetricInterpole.opt-1;
+
+		double * L= LastMetricInterpole.L, *S = LastMetricInterpole.S;
+		// warning for optimisation S is the abcisse in [0:0.5]
+		// and L is le lenght 
+		if(l<=L[0]){
+			r=2*S[0]*l/L[0];
+		}
+		else if (l>=L[j]){
+			r=1;
+		}
+		else{
+			int i=0;
+			while (j-i>1){
+				int k;
+				k= (i+j)/2;
+				if(l<=L[k]){
+					j=k;// l<=L[j] 
+				}
+				else{
+					i=k; //  L[i]<l
+				}
+			};
+			if (i==j){
+				r = 2*S[i];
+			}
+			else{
+				r =  2*(S[i]*(L[j]-l)+ S[j]*(l-L[i]))/(L[j]-L[i]);
+			}
+		}
+		if (r>1 || r<0){
+			_error_("r>1 || r<0");
+		}
+		return r ;
+	}
+	/*}}}*/
+
+}
Index: /issm/trunk/src/c/bamg/Metric.h
===================================================================
--- /issm/trunk/src/c/bamg/Metric.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/Metric.h	(revision 15396)
@@ -0,0 +1,138 @@
+#ifndef _METRIC_H
+#define _METRIC_H
+
+#include "./include.h"
+#include "../shared/shared.h"
+#include "R2.h"
+#include <math.h>
+
+namespace bamg {
+
+	typedef P2<double,double>    D2;
+	typedef P2xP2<double,double> D2xD2;
+
+	class Metric;
+	class EigenMetric;
+
+	class Metric{
+
+		public:
+
+			//fields
+			double a11,a21,a22;
+
+			//friends
+			friend class EigenMetric;
+
+			//functions
+			Metric():a11(0),a21(0),a22(0){};
+			Metric(const EigenMetric&);
+			Metric(double a);
+			Metric(double a,double b,double c);
+			Metric( double  a,const  Metric& ma, double  b,const  Metric& mb);
+			Metric(const double  a[3],const  Metric& m0,const  Metric& m1,const  Metric& m2 );
+			void        Echo();
+			R2          mul(const R2 x)const;
+			double      det() const;
+			int         IntersectWith(const  Metric& M2);
+			inline void Box(double &hx,double &hy) const;
+
+			/*The following functions must remain the the header file because it is called before Metric
+			 * is compiled by other classes*/
+			R2 Orthogonal(const R2 x){ return R2(-(a21*x.x+a22*x.y),a11*x.x+a21*x.y); }
+			R2 Orthogonal(const I2 x){ return R2(-(a21*x.x+a22*x.y),a11*x.x+a21*x.y); }
+
+			//operators
+			Metric operator*(double c) const {double c2=c*c;return  Metric(a11*c2,a21*c2,a22*c2);} 
+			Metric operator/(double c) const {double c2=1/(c*c);return  Metric(a11*c2,a21*c2,a22*c2);} 
+			operator D2xD2(){ return D2xD2(a11,a21,a21,a22);}
+			double  operator()(R2 x) const { return sqrt(x.x*x.x*a11+2*x.x*x.y*a21+x.y*x.y*a22);};        // length of x in metric sqrt(<Mx,x>)
+			double  operator()(R2 x,R2 y) const { return x.x*y.x*a11+(x.x*x.y+x.y*y.x)*a21+x.y*y.y*a22;};
+
+	};
+
+	class EigenMetric{
+		public:
+
+			//fields
+			double lambda1,lambda2;
+			D2     v;
+
+			//friends
+			friend  class Metric;
+
+			//functions
+			EigenMetric(const Metric& );
+			EigenMetric(double r1,double r2,const D2& vp1);
+			void   Echo();
+			void   Abs();
+			void   pow(double  p);
+			void   Min(double  a);
+			void   Max(double  a);
+			void   Minh(double h);
+			void   Maxh(double h);
+			void   Isotrope();
+			double hmin()   const;
+			double hmax()   const;
+			double lmax()   const;
+			double lmin()   const;
+			double Aniso2() const;
+			double Aniso()  const;
+			void   BoundAniso(const  double c);
+			inline void BoundAniso2(const double coef);
+
+			//operators
+			void operator *=(double coef){ lambda1*=coef;lambda2*=coef;}
+	};
+
+	class SaveMetricInterpole {
+		friend double LengthInterpole(const Metric& Ma,const  Metric& Mb, R2 AB);
+		friend double abscisseInterpole(const Metric& Ma ,const  Metric& Mb, R2 ,double s,int optim);
+		public:
+		int opt;
+		double lab;
+		double L[1024],S[1024];
+	};
+
+	extern SaveMetricInterpole  LastMetricInterpole; // for optimization 
+	//Functions
+	void  SimultaneousMatrixReduction( Metric M1,  Metric M2,D2xD2 &V);
+	double LengthInterpole(const Metric& Ma,const  Metric& Mb, R2 AB);
+	double abscisseInterpole(const Metric& Ma,const  Metric& Mb, R2 AB,double s,int optim=0);
+
+	//inlines
+	inline void  EigenMetric::BoundAniso2(const double coef){
+		if (coef<=1.00000000001){
+			if (lambda1 < lambda2)
+			 lambda1 = bamg::Max(lambda1,lambda2*coef);
+			else
+			 lambda2 = bamg::Max(lambda2,lambda1*coef);
+		}
+		else{  //TO BE CHECKED
+			if (lambda1 > lambda2)
+			 lambda1 = bamg::Min(lambda1,lambda2*coef);
+			else
+			 lambda2 = bamg::Min(lambda2,lambda1*coef);
+		}
+	}
+	inline Metric::Metric(const EigenMetric& M) {
+		double v00=M.v.x*M.v.x;
+		double v11=M.v.y*M.v.y;
+		double v01=M.v.x*M.v.y;
+		a11=v00*M.lambda1+v11*M.lambda2;
+		a21=v01*(M.lambda1-M.lambda2);
+		a22=v00*M.lambda2+v11*M.lambda1;
+	}
+	inline   void  Metric::Box(double &hx,double &hy) const {
+		double d=  a11*a22-a21*a21;
+		hx = sqrt(a22/d);
+		hy = sqrt(a11/d);
+	}
+	inline double LengthInterpole(double la,double lb) {
+		return ( Abs(la - lb) < 1.0e-6*Max3(la,lb,1.0e-20) ) ?  (la+lb)/2  : la*lb*log(la/lb)/(la-lb);
+	}
+	inline double abscisseInterpole(double la,double lb,double lab,double s){
+		return ( Abs(la - lb) <1.0e-6*Max3(la,lb,1.0e-20))  ? s : (exp(s*lab*(la-lb)/(la*lb))-1)*lb/(la-lb);
+	}
+}
+#endif
Index: /issm/trunk/src/c/bamg/R2.h
===================================================================
--- /issm/trunk/src/c/bamg/R2.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/R2.h	(revision 15396)
@@ -0,0 +1,101 @@
+/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, R2.h)*/
+#ifndef _R2_H
+#define _R2_H
+
+#include <cstdio>
+#include "../shared/shared.h"
+
+namespace bamg {
+
+	template <class R,class RR> class P2{
+
+		  public:  
+
+			  //fields
+			  R x,y;
+
+			  //functions
+			  P2 () :x(0),y(0) {};
+			  P2 (R a,R b)  :x(a),y(b)  {}
+			  P2 (P2 A,P2 B) : x(B.x-A.x),y(B.y-A.y) {}
+			  void Echo(){
+				  printf("Member of P2:\n");
+				  printf("   x: %g or %i\n",x,x);
+				  printf("   y: %g or %i\n",y,y);
+			  }
+			  //operators
+			  RR       operator,(const P2<R,RR> & cc) const {return  (RR) x* (RR) cc.x+(RR) y* (RR) cc.y;} //scalar product
+			  P2<R,RR> operator+(const P2<R,RR> & cc) const {return P2<R,RR>(x+cc.x,y+cc.y);}
+			  P2<R,RR> operator-(const P2<R,RR> & cc) const {return P2<R,RR>(x-cc.x,y-cc.y);}
+			  P2<R,RR> operator-()  const{return P2<R,RR>(-x,-y);}
+			  P2<R,RR> operator*(R  cc) const {return P2<R,RR>(x*cc,y*cc);}
+			  P2<R,RR> operator/(R  cc) const {return P2<R,RR>(x/cc,y/cc);}
+			  P2<R,RR> operator+=(const  P2<R,RR> & cc) {x += cc.x;y += cc.y;return *this;}
+			  P2<R,RR> operator/=(const  R r) {x /= r;y /= r;return *this;}
+			  P2<R,RR> operator*=(const  R r) {x *= r;y *= r;return *this;}
+			  P2<R,RR> operator-=(const  P2<R,RR> & cc) {x -= cc.x;y -= cc.y;return *this;}
+
+	  };
+
+	template <class R,class RR> class P2xP2{
+
+		  public:
+
+			  //fields
+			  P2<R,RR> x,y; 
+
+			  //functions
+			  P2xP2 (): x(),y()  {}
+			  P2xP2 (P2<R,RR> a,P2<R,RR> b): x(a),y(b) {}
+			  P2xP2 (P2<R,RR> a,P2<R,RR> b,P2<R,RR> c ): x(b-a),y(c-a) {}
+			  P2xP2 (R xx,R xy,R yx,R yy) :x(xx,xy),y(yx,yy) {}
+			  void Echo(){
+				  printf("Member of P2xP2:\n");
+				  printf("   x.x: %g   x.y: %g\n",x.x,x.y);
+				  printf("   y.x: %g   y.x: %g\n",y.x,y.y);
+			  }
+			  RR          det() const {return (RR) x.x* (RR) y.y - (RR) x.y * (RR) y.x;}
+			  P2xP2<R,RR> inv()  const{
+				  RR d = (*this).det(); 
+				  return P2xP2<R,RR>((R)( y.y /d) ,(R)(-x.y/d),(R)( -y.x/d) ,(R)( x.x/d) );
+			  };
+			  P2xP2<R,RR> t()  {return P2xP2<R,RR>(x.x,y.x,x.y,y.y);} //transposer 
+			  P2<R,RR>    tx() {return P2<R,RR>(x.x,y.x);} 
+			  P2<R,RR>    ty() {return P2<R,RR>(x.y,y.y);} 
+			  //Operators
+			  P2<R,RR>     operator*(const P2<R,RR>& c) const {return P2<R,RR>(x.x*c.x + x.y*c.y, y.x*c.x + y.y*c.y);}
+			  P2xP2<R,RR>  operator*(P2xP2<R,RR> c) const{
+				  return  P2xP2<R,RR>(x.x*c.x.x + x.y*c.y.x,
+							  x.x*c.x.y + x.y*c.y.y,
+							  y.x*c.x.x + y.y*c.y.x,
+							  y.x*c.x.y + y.y*c.y.y);
+			  }
+	  };  
+
+	//inline functions
+	template  <class R,class RR>  
+	  inline RR Det(const P2<R,RR> x,const P2<R,RR> y) {
+		  return (RR) x.x * (RR) y.y - (RR) x.y * (RR) y.x ;
+	  } 
+	template  <class R,class RR>  
+	  inline RR Area2 (const P2<R,RR> a,const P2<R,RR> b,const P2<R,RR> c) {
+		  return Det(b-a,c-a) ;
+	  }
+	template  <class R,class RR>  
+	  inline R Norme1 (const P2<R,RR> x) {
+		  return (Abs(x.x)+Abs(x.y)) ;
+	  } 
+	template  <class R,class RR>  
+	  inline RR Norme2_2 (const P2<R,RR> x) {
+		  return (RR)x.x*(RR)x.x + (RR)x.y*(RR)x.y ;
+	  } 
+	template  <class R,class RR>  
+	  inline RR Norme2 (const P2<R,RR> x) {
+		  return sqrt((RR)x.x*(RR)x.x + (RR)x.y*(RR)x.y) ;
+	  } 
+	template  <class R,class RR>  
+	  inline P2<R,RR> Orthogonal (const P2<R,RR> x) {
+		  return  P2<R,RR>(-x.y,x.x);
+	  } 
+}
+#endif
Index: /issm/trunk/src/c/bamg/SetOfE4.cpp
===================================================================
--- /issm/trunk/src/c/bamg/SetOfE4.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/SetOfE4.cpp	(revision 15396)
@@ -0,0 +1,120 @@
+#include "./bamgobjects.h"
+
+using namespace std;
+namespace bamg {
+
+	/*Constructor*/
+	/*FUNCTION  SetOfEdges4::SetOfEdges4(long mmx,long nnx){{{*/
+	SetOfEdges4::SetOfEdges4(long mmx,long nnx){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, SetOfEdges4.cpp/SetOfEdges4)*/
+
+		/*Intermediary*/
+		int i;
+
+		//initialize fields
+		nx   =nnx;   //number of vertices
+		nbax =mmx;   // 3 * number of triangles
+		NbOfEdges=0;
+		head = new long [nx];
+		Edges= new IntEdge[nbax];
+
+		//initialize head (-1 everywhere)
+		i=nx;
+		while(i--) head[i]=-1;
+	}
+	/*}}}*/
+
+	/*Methods*/ 
+	/*FUNCTION  SetOfEdges4::add{{{*/
+	long SetOfEdges4::add(long ii,long jj) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, SetOfEdges4.cpp/add)*/
+
+		/*Intermediary*/
+		int h,n;
+
+		//get n from h (usually h=ii)
+		_assert_(head);
+		n=head[h=Abs(ii)%nx];
+
+		//go through the existing edges that holds h (=ii) and check that 
+		//the edge ii jj is not already in Edge
+		while (n >= 0){
+
+			//if the edge ii jj is already in Edges, return n
+			if (ii == Edges[n].i && jj == Edges[n].j) return n;
+
+			//else go to next edge that holds ii
+			else n = Edges[n].next;
+		}
+
+		//check that nbax <=NbOfEdges
+		if (nbax <=NbOfEdges ) {
+			_error_("SetOfEdges4::add overflow: NbOfEdges=" << NbOfEdges << " > nbax=" << nbax);
+		}
+
+		//update chain
+		Edges[NbOfEdges].i=ii;
+		Edges[NbOfEdges].j=jj;
+		Edges[NbOfEdges].next= head[h];
+		head[h] = NbOfEdges;
+		return NbOfEdges ++;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::find {{{*/
+	long SetOfEdges4::find(long ii,long jj) { 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, SetOfEdges4.cpp/find)*/
+
+		/*Intermediary*/
+		int n;
+
+		//check that head is not empty
+		_assert_(head);
+
+		//get n from h (usually h=ii)
+		n=head[Abs(ii)%nx];
+
+		//go through the existing edges that holds h (=ii) and return position in Edge
+		while (n >= 0){
+
+			//if the edge ii jj is already in Edges, return n
+			if (ii == Edges[n].i && jj == Edges[n].j) return n;
+
+			//else go to next edge that holds ii
+			else n = Edges[n].next;
+		}
+
+		//if we reach this point, the edge does not exist return -1
+		return -1;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::i{{{*/
+	long SetOfEdges4::i(long k){
+		return Edges[k].i;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::j{{{*/
+	long SetOfEdges4::j(long k){
+		return Edges[k].j;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::nb{{{*/
+	long SetOfEdges4::nb(){
+		return NbOfEdges;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::newarete{{{*/
+	long SetOfEdges4::newarete(long k){
+		return NbOfEdges == k+1;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::SortAndAdd{{{*/
+	long SetOfEdges4::SortAndAdd (long ii,long jj) {
+		return ii <=jj ? add (ii,jj)  : add (jj,ii) ;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::SortAndFind{{{*/
+	long SetOfEdges4::SortAndFind (long ii,long jj) {
+		return ii <=jj ? find (ii,jj)  : find (jj,ii) ;
+	}
+	/*}}}*/
+}
Index: /issm/trunk/src/c/bamg/SetOfE4.h
===================================================================
--- /issm/trunk/src/c/bamg/SetOfE4.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/SetOfE4.h	(revision 15396)
@@ -0,0 +1,42 @@
+#ifndef _SetOfEdge4_h
+#define _SetOfEdge4_h
+
+namespace bamg {
+
+	class SetOfEdges4;
+
+	class IntEdge{
+		friend class SetOfEdges4;
+		public:
+		long i,j;
+		long next; 
+	};
+
+	class SetOfEdges4 {
+
+		private:
+			long nx,nbax,NbOfEdges;
+			long* head; 
+			IntEdge* Edges;
+
+		public:
+
+			// Constructors
+			SetOfEdges4(long ,long);// nb Edges mx , nb de sommet 
+			~SetOfEdges4() {delete [] head; delete [] Edges;}
+
+			//operators
+			IntEdge & operator[](long k){return  Edges[k];}
+
+			//Methods
+			long add (long ii,long jj);
+			long SortAndAdd (long ii,long jj);
+			long nb();
+			long find (long ii,long jj);
+			long SortAndFind (long ii,long jj);
+			long i(long k);
+			long j(long k);
+			long newarete(long k);
+	};
+}
+#endif 
Index: /issm/trunk/src/c/bamg/SubDomain.cpp
===================================================================
--- /issm/trunk/src/c/bamg/SubDomain.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/SubDomain.cpp	(revision 15396)
@@ -0,0 +1,28 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "SubDomain.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	/*FUNCTION SubDomain::Set {{{*/
+	void SubDomain::Set(const Mesh & Th ,long i,Mesh & ThNew){
+		*this = Th.subdomains[i];
+		if ( head-Th.triangles<0 || head-Th.triangles>=Th.nbt){
+			_error_("head-Th.triangles<0 || head-Th.triangles>=Th.nbt");
+		}
+		head = ThNew.triangles + Th.GetId(head) ; 
+		if (edge-Th.edges<0 || edge-Th.edges>=Th.nbe);{
+			_error_("edge-Th.edges<0 || edge-Th.edges>=Th.nbe");
+		}
+		edge = ThNew.edges+ Th.GetId(edge);
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/SubDomain.h
===================================================================
--- /issm/trunk/src/c/bamg/SubDomain.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/SubDomain.h	(revision 15396)
@@ -0,0 +1,26 @@
+#ifndef _SUBDOMAIN_H_
+#define _SUBDOMAIN_H_
+
+#include "./include.h"
+#include "./Edge.h"
+
+namespace bamg {
+
+	class Triangle;
+	class Mesh;
+
+	class SubDomain {
+
+		public:
+
+			Triangle *head;
+			long      ReferenceNumber;
+			int       direction;   // -1 or 1
+			Edge     *edge;        // to geometrical
+
+			//Methods
+			void Set(const Mesh &,long,Mesh &);
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/Triangle.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Triangle.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/Triangle.cpp	(revision 15396)
@@ -0,0 +1,492 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "./bamgobjects.h"
+#include "../shared/shared.h"
+#include "./det.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Triangle(){{{*/
+	Triangle::Triangle(void){
+
+	}
+	/*}}}*/
+	/*FUNCTION Triangle(Mesh *Th,long i,long j,long k) {{{*/
+	Triangle::Triangle(Mesh *Th,long i,long j,long k) {
+		BamgVertex *v=Th->vertices;
+		long nbv = Th->nbv;
+		if (i<0 || j<0 || k<0){
+			_error_("i<0 || j<0 || k<0");
+		}
+		if (i>=nbv || j>=nbv || k>=nbv){
+			_error_("i>=nbv || j>=nbv || k>=nbv");
+		}
+		vertices[0]=v+i;
+		vertices[1]=v+j;
+		vertices[2]=v+k;
+		adj[0]=adj[1]=adj[2]=0;
+		AdjEdgeIndex[0]=AdjEdgeIndex[1]=AdjEdgeIndex[2]=0;
+		det=0;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2) {{{*/
+	Triangle::Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2){
+		vertices[0]=v0;
+		vertices[1]=v1;
+		vertices[2]=v2;
+		adj[0]=adj[1]=adj[2]=0;
+		AdjEdgeIndex[0]=AdjEdgeIndex[1]=AdjEdgeIndex[2]=0;
+		if (v0) det=0;
+		else {
+			det=-1;
+			link=NULL;};  
+	}
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Triangle::Adj{{{*/
+	AdjacentTriangle Triangle::Adj(int i)  const {
+		return AdjacentTriangle(adj[i],AdjEdgeIndex[i]&3);
+	};/*}}}*/
+	/*FUNCTION Triangle::Anisotropy{{{*/
+	double Triangle::Anisotropy() const{
+
+		double lmin,lmax;
+
+		/*Get three vertices A,B and C*/
+		R2 A=*this->vertices[0];
+		R2 B=*this->vertices[1];
+		R2 C=*this->vertices[2];
+
+		/*Compute edges*/
+		R2 e1=B-A;
+		R2 e2=C-A;
+		R2 e3=B-C;
+
+		/*Compute edge length*/
+		double l1=Norme2(e1);
+		double l2=Norme2(e2);
+		double l3=Norme2(e3);
+
+		lmin=l1;
+		lmin=min(lmin,l2);
+		lmin=min(lmin,l3);
+		lmax=l1;
+		lmax=max(lmax,l2);
+		lmax=max(lmax,l3);
+
+		return lmax/lmin;
+	};/*}}}*/
+	/*FUNCTION Triangle::Length{{{*/
+	double Triangle::Length() const{
+
+		double l;
+
+		/*Get three vertices A,B and C*/
+		R2 A=*this->vertices[0];
+		R2 B=*this->vertices[1];
+		R2 C=*this->vertices[2];
+
+		/*Compute edges*/
+		R2 e1=B-A;
+		R2 e2=C-A;
+		R2 e3=B-C;
+
+		/*Compute edge length*/
+		l=Norme2(e1);
+		l=max(l,Norme2(e2));
+		l=max(l,Norme2(e3));
+
+		return l;
+	};/*}}}*/
+	/*FUNCTION Triangle::Echo {{{*/
+	void Triangle::Echo(void){
+
+		int i;
+
+		_printf_("Triangle:\n");
+		_printf_("   vertices pointer towards three vertices\n");
+		_printf_("      vertices[0] vertices[1] vertices[2] = " << vertices[0] << " " << vertices[1] << " " << vertices[2] << "\n");
+		_printf_("   adj pointer towards three adjacent triangles\n");
+		_printf_("      adj[0] adj[1] adj[2] = " << adj[0] << " " << adj[1] << " " << adj[2] << "\n");
+		_printf_("   det (integer triangle determinant) = " << det << "\n");
+		if (link){
+			_printf_("   link (pointer toward duplicate triangle)= " << link << "\n");
+		}
+		else{
+			_printf_("   color = " << color << "\n");
+		}
+
+		_printf_("\nThree vertices:\n");
+		for(i=0;i<3;i++){
+			if (vertices[i]){
+				vertices[i]->Echo();
+			}
+			else{
+				_printf_("   vertex " << i+1 << " does not exist\n");
+			}
+		}
+
+		return;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::FindBoundaryEdge{{{*/
+	AdjacentTriangle Triangle::FindBoundaryEdge(int i) const{
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindBoundaryEdge)*/
+
+		/*Intermediary*/
+		Triangle* ttc=NULL;
+		int k,j,jc;
+
+		// call current triangle t
+		Triangle* t = (Triangle*)this;
+
+		//is the current triangle inside or outside?
+		int outside=!link  ;
+
+		// EdgesVertexTriangle[3][2] = {{1,2},{2,0},{0,1}};
+		// initialize j as the first vertex of the ith edge
+		j=EdgesVertexTriangle[i][0];
+
+		//Loop over the adjacent triangle of t
+		k=0;
+		do{
+			//keep track of outside
+			int outsidep = outside;
+			//increment k
+			k++;
+			//Get ttc, adjacent triangle of t with respect to vertex j
+			ttc =  t->adj[j];
+			//is the current triangle inside or outside?
+			outside = !ttc->link;
+			//if both previous triangle are outside, return
+			if (outside+outsidep == 1) return AdjacentTriangle(t,j);
+
+			//update t and j
+			t = ttc;
+			//NextEdge[3] = {1,2,0};
+			jc = NextEdge[t->AdjEdgeIndex[j]&3];
+			j = NextEdge[jc];
+
+			//check number of iterations
+			if (k>=2000){
+				_error_("too many iteration in Triangle::FindBoundaryEdge (k>=2000)");
+			}
+		} while (this!= t);
+		//not found, return empty triangle
+		return AdjacentTriangle(NULL,0);
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::GetAllflag{{{*/
+	int    Triangle::GetAllflag(int a){
+		return AdjEdgeIndex[a] & 1020;
+	}/*}}}*/
+	/*FUNCTION Triangle::Hidden{{{*/
+	int    Triangle::Hidden(int a)const {
+		return AdjEdgeIndex[a]&16;
+	} /*}}}*/
+	/*FUNCTION Triangle::Locked{{{*/
+	int    Triangle::Locked(int a)const {
+		return AdjEdgeIndex[a]&4;
+	} /*}}}*/
+	/*FUNCTION Triangle::NuEdgeTriangleAdj{{{*/
+	short  Triangle::NuEdgeTriangleAdj(int i) const {
+		/*Number of the  adjacent edge in adj tria (make sure it is between 0 and 2*/
+		return AdjEdgeIndex[i&3]&3;
+	}/*}}}*/
+	/*FUNCTION Triangle::Optim{{{*/
+	long  Triangle::Optim(short i,int koption) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Optim)*/
+
+		// turn around (positive direction)
+		Triangle *t=this;
+		long NbSwap =0;
+		int  k = 0;
+		int  j = OppositeEdge[i];
+		int  jp= PreviousEdge[j];
+
+		// initialize tp, jp the previous triangle & edge
+		Triangle *tp=adj[jp];
+		jp = AdjEdgeIndex[jp]&3;
+		do {
+			while (t->swap(j,koption)){
+				if (k>=20000) _error_("k>=20000");
+				NbSwap++;
+				k++;
+				t=  tp->adj[jp];      // set unchange t qnd j for previous triangles
+				j=  NextEdge[tp->AdjEdgeIndex[jp]&3];
+			}
+			// end on this  Triangle 
+			tp = t;
+			jp = NextEdge[j];
+
+			t=  tp->adj[jp];      // set unchange t qnd j for previous triangles
+			j=  NextEdge[tp->AdjEdgeIndex[jp]&3];
+
+		} while( t != this);
+		return NbSwap;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::Quadrangle {{{*/
+	Triangle* Triangle::Quadrangle(BamgVertex * & v0,BamgVertex * & v1,BamgVertex * & v2,BamgVertex * & v3) const{
+		// return the other triangle of the quad if a quad or 0 if not a quat
+		Triangle * t =0;
+		if (link) {
+			int a=-1;
+			if (AdjEdgeIndex[0] & 16 ) a=0;
+			if (AdjEdgeIndex[1] & 16 ) a=1;
+			if (AdjEdgeIndex[2] & 16 ) a=2;
+			if (a>=0) {
+				t = adj[a];
+				//  if (t-this<0) return 0;
+				v2 = vertices[VerticesOfTriangularEdge[a][0]];
+				v0 = vertices[VerticesOfTriangularEdge[a][1]];
+				v1 = vertices[OppositeEdge[a]];
+				v3 = t->vertices[OppositeEdge[AdjEdgeIndex[a]&3]];
+			}
+		}
+		return t;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::QualityQuad {{{*/
+	double   Triangle::QualityQuad(int a,int option) const{
+		double q;
+		if (!link || AdjEdgeIndex[a] &4)
+		 q=  -1;
+		else {
+			Triangle * t = adj[a];
+			if (t-this<0) q=  -1;// because we do 2 times 
+			else if (!t->link ) q=  -1;
+			else if (AdjEdgeIndex[0] & 16 || AdjEdgeIndex[1] & 16  || AdjEdgeIndex[2] & 16 || t->AdjEdgeIndex[0] & 16 || t->AdjEdgeIndex[1] & 16 || t->AdjEdgeIndex[2] & 16 )
+			 q= -1;
+			else if(option){ 
+				const BamgVertex & v2 = *vertices[VerticesOfTriangularEdge[a][0]];
+				const BamgVertex & v0 = *vertices[VerticesOfTriangularEdge[a][1]];
+				const BamgVertex & v1 = *vertices[OppositeEdge[a]];
+				const BamgVertex & v3 = * t->vertices[OppositeEdge[AdjEdgeIndex[a]&3]];
+				q =  QuadQuality(v0,v1,v2,v3); // do the float part
+			}
+			else q= 1;
+		}
+		return  q;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::Renumbering(Triangle *tb,Triangle *te, long *renu){{{*/
+	void  Triangle::Renumbering(Triangle *tb,Triangle *te, long *renu){
+
+		if (link  >=tb && link  <te) link  = tb + renu[link -tb];
+		if (adj[0] >=tb && adj[0] <te) adj[0] = tb + renu[adj[0]-tb];
+		if (adj[1] >=tb && adj[1] <te) adj[1] = tb + renu[adj[1]-tb];
+		if (adj[2] >=tb && adj[2] <te) adj[2] = tb + renu[adj[2]-tb];    
+	}/*}}}*/
+	/*FUNCTION Triangle::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){{{*/
+	void Triangle::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){
+		if (vertices[0] >=vb && vertices[0] <ve) vertices[0] = vb + renu[vertices[0]-vb];
+		if (vertices[1] >=vb && vertices[1] <ve) vertices[1] = vb + renu[vertices[1]-vb];
+		if (vertices[2] >=vb && vertices[2] <ve) vertices[2] = vb + renu[vertices[2]-vb];    
+	}/*}}}*/
+	/*FUNCTION Triangle::Set {{{*/
+	void Triangle::Set(const Triangle & rec,const Mesh & Th ,Mesh & ThNew){ 
+		*this = rec;
+		if ( vertices[0] ) vertices[0] = ThNew.vertices +  Th.GetId(vertices[0]);
+		if ( vertices[1] ) vertices[1] = ThNew.vertices +  Th.GetId(vertices[1]);
+		if ( vertices[2] ) vertices[2] = ThNew.vertices +  Th.GetId(vertices[2]);
+		if(adj[0]) adj[0] =  ThNew.triangles + Th.GetId(adj[0]);
+		if(adj[1]) adj[1] =  ThNew.triangles + Th.GetId(adj[1]);
+		if(adj[2]) adj[2] =  ThNew.triangles + Th.GetId(adj[2]);
+		if (link  >= Th.triangles && link  < Th.triangles + Th.nbt)
+		 link = ThNew.triangles + Th.GetId(link);
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::SetAdjAdj{{{*/
+	void Triangle::SetAdjAdj(short a){
+		// Copy all the mark 
+		a &= 3;
+		register Triangle *tt=adj[a];
+		AdjEdgeIndex [a] &= 55; // remove MarkUnSwap
+		register short aatt = AdjEdgeIndex[a] & 3;
+		if(tt){ 
+			tt->adj[aatt]=this;
+			tt->AdjEdgeIndex[aatt]=a + (AdjEdgeIndex[a] & 60 ) ;
+		}
+	}/*}}}*/
+	/*FUNCTION Triangle::SetAdj2{{{*/
+	void Triangle::SetAdj2(short a,Triangle *t,short aat){
+		/*For current triangle:
+		 * - a is the index of the edge were the adjency is set (in [0 2])
+		 * - t is the adjacent triangle
+		 * - aat is the index of the same edge in the adjacent triangle*/
+		adj[a]=t;
+		AdjEdgeIndex[a]=aat;
+		if(t){ //if t!=NULL add adjacent triangle to t (this)
+			t->adj[aat]=this;
+			t->AdjEdgeIndex[aat]=a;
+		}
+	}/*}}}*/
+	/*FUNCTION Triangle::SetAllFlag{{{*/
+	void   Triangle::SetAllFlag(int a,int f){
+		AdjEdgeIndex[a] = (AdjEdgeIndex[a] &3) + (1020 & f);
+	}/*}}}*/
+	/*FUNCTION Triangle::SetDet{{{*/
+	void Triangle::SetDet() {
+		if(vertices[0] && vertices[1] && vertices[2])    det = bamg::det(*vertices[0],*vertices[1],*vertices[2]);
+		else det = -1; 
+	}/*}}}*/
+	/*FUNCTION Triangle::SetHidden{{{*/
+	void Triangle::SetHidden(int a){
+		//Get Adjacent Triangle number a
+		register Triangle* t = adj[a];
+		//if it exist
+		//C|=D -> C=(C|D) bitwise inclusive OR
+		if(t) t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=16;
+		AdjEdgeIndex[a] |= 16;
+	}/*}}}*/
+	/*FUNCTION Triangle::SetLocked{{{*/
+	void Triangle::SetLocked(int a){
+		//mark the edge as on Boundary
+		register Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=4;
+		AdjEdgeIndex[a] |= 4;
+	}/*}}}*/
+	/*FUNCTION Triangle::SetMarkUnSwap{{{*/
+	void Triangle::SetMarkUnSwap(int a){
+		register Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=8;
+		AdjEdgeIndex[a] |=8 ;
+	}/*}}}*/
+	/*FUNCTION Triangle::SetSingleVertexToTriangleConnectivity{{{*/
+	void Triangle::SetSingleVertexToTriangleConnectivity() { 
+		if (vertices[0]) (vertices[0]->t=this,vertices[0]->IndexInTriangle=0);
+		if (vertices[1]) (vertices[1]->t=this,vertices[1]->IndexInTriangle=1);
+		if (vertices[2]) (vertices[2]->t=this,vertices[2]->IndexInTriangle=2);
+	}/*}}}*/
+	/*FUNCTION Triangle::SetUnMarkUnSwap{{{*/
+	void Triangle::SetUnMarkUnSwap(int a){ 
+		register Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] &=55; // 23 + 32 
+		AdjEdgeIndex[a] &=55 ;
+	}/*}}}*/
+	/*FUNCTION Triangle::swap{{{*/
+	int Triangle::swap(short a,int koption){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
+
+		if(a/4 !=0) return 0;// arete lock or MarkUnSwap
+
+		register Triangle *t1=this,*t2=adj[a];// les 2 triangles adjacent
+		register short a1=a,a2=AdjEdgeIndex[a];// les 2 numero de l arete dans les 2 triangles
+		if(a2/4 !=0) return 0; // arete lock or MarkUnSwap
+
+		register BamgVertex  *sa=t1->vertices[VerticesOfTriangularEdge[a1][0]];
+		register BamgVertex  *sb=t1->vertices[VerticesOfTriangularEdge[a1][1]];
+		register BamgVertex  *s1=t1->vertices[OppositeVertex[a1]];
+		register BamgVertex  *s2=t2->vertices[OppositeVertex[a2]];
+
+		Icoor2 det1=t1->det , det2=t2->det ;
+		Icoor2 detT = det1+det2;
+		Icoor2 detA = Abs(det1) + Abs(det2);
+		Icoor2 detMin = Min(det1,det2);
+
+		int OnSwap = 0;       
+		// si 2 triangle infini (bord) => detT = -2;
+		if (sa == 0) {// les deux triangles sont frontieres
+			det2=bamg::det(s2->i,sb->i,s1->i);
+			OnSwap = det2 >0;}
+		else if (sb == 0) { // les deux triangles sont frontieres
+			det1=bamg::det(s1->i,sa->i,s2->i);
+			OnSwap = det1 >0;}
+		else if(( s1 != 0) && (s2 != 0) ) {
+			det1 = bamg::det(s1->i,sa->i,s2->i);
+			det2 = detT - det1;
+			OnSwap = (Abs(det1) + Abs(det2)) < detA;
+
+			Icoor2 detMinNew=Min(det1,det2);
+			//     if (detMin<0 && (Abs(det1) + Abs(det2) == detA)) OnSwap=BinaryRand();// just for test   
+			if (! OnSwap &&(detMinNew>0)) {
+				OnSwap = detMin ==0;
+				if (! OnSwap) {
+					int  kopt = koption;
+					while (1)
+					 if(kopt) {
+						 // critere de Delaunay pure isotrope
+						 register Icoor2 xb1 = sb->i.x - s1->i.x,
+									 x21 = s2->i.x - s1->i.x,
+									 yb1 = sb->i.y - s1->i.y,
+									 y21 = s2->i.y - s1->i.y,
+									 xba = sb->i.x - sa->i.x, 
+									 x2a = s2->i.x - sa->i.x,
+									 yba = sb->i.y - sa->i.y,
+									 y2a = s2->i.y - sa->i.y;
+						 register double
+							cosb12 =  double(xb1*x21 + yb1*y21),
+									 cosba2 =  double(xba*x2a + yba*y2a) ,
+									 sinb12 = double(det2),
+									 sinba2 = double(t2->det);
+
+						 // angle b12 > angle ba2 => cotg(angle b12) < cotg(angle ba2)
+						 OnSwap =  ((double) cosb12 * (double)  sinba2) <  ((double) cosba2 * (double) sinb12);
+						 break;
+					 }
+					 else {	
+						 // critere de Delaunay anisotrope 
+						 double som;
+						 I2 AB=(I2) *sb - (I2) *sa;
+						 I2 MAB2=((I2) *sb + (I2) *sa);
+						 R2 MAB(MAB2.x*0.5,MAB2.y*0.5);
+						 I2 A1=(I2) *s1 - (I2) *sa;
+						 I2 D = (I2) * s1 - (I2) * sb ;
+						 R2 S2(s2->i.x,s2->i.y);
+						 R2 S1(s1->i.x,s1->i.y);
+							{
+							 Metric M=s1->m;
+							 R2 ABo = M.Orthogonal(AB);
+							 R2 A1o = M.Orthogonal(A1);
+							 // (A+B)+ x ABo = (S1+B)/2+ y A1 
+							 // ABo x - A1o y =  (S1+B)/2-(A+B)/2 = (S1-B)/2 = D/2
+							 double dd = Abs(ABo.x*A1o.y)+Abs(ABo.y*A1o.x);
+							 double d = (ABo.x*A1o.y - ABo.y*A1o.x)*2; // because D/2
+							 if (Abs(d) > dd*1.e-3) {
+								 R2 C(MAB+ABo*((D.x*A1o.y - D.y*A1o.x)/d));
+								 som  = M(C - S2)/M(C - S1);
+							 } else 
+								{kopt=1;continue;}
+
+							}
+							{
+							 Metric M=s2->m;
+							 R2 ABo = M.Orthogonal(AB);
+							 R2 A1o = M.Orthogonal(A1);
+							 // (A+B)+ x ABo = (S1+B)/2+ y A1 
+							 // ABo x - A1o y =  (S1+B)/2-(A+B)/2 = (S1-B)/2 = D/2 
+							 double dd = Abs(ABo.x*A1o.y)+Abs(ABo.y*A1o.x);
+							 double d = (ABo.x*A1o.y - ABo.y*A1o.x)*2; // because D/2
+							 if(Abs(d) > dd*1.e-3) {
+								 R2 C(MAB+ABo*((D.x*A1o.y - D.y*A1o.x)/d));
+								 som  += M(C - S2)/M(C -  S1);
+							 } else 
+								{kopt=1;continue;}
+							}
+						 OnSwap = som < 2;
+						 break;
+					 }
+
+				} // OnSwap 
+			} // (! OnSwap &&(det1 > 0) && (det2 > 0) )
+		}
+		if( OnSwap ) 
+		 bamg::swap(t1,a1,t2,a2,s1,s2,det1,det2);
+		else {
+			t1->SetMarkUnSwap(a1);     
+		}
+		return OnSwap;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::TriangleAdj{{{*/
+	Triangle* Triangle::TriangleAdj(int i) const {
+		return adj[i&3];
+	}/*}}}*/
+
+}
Index: /issm/trunk/src/c/bamg/Triangle.h
===================================================================
--- /issm/trunk/src/c/bamg/Triangle.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/Triangle.h	(revision 15396)
@@ -0,0 +1,75 @@
+#ifndef _TRIANGLE_H_
+#define _TRIANGLE_H_
+
+#include "./include.h"
+#include "AdjacentTriangle.h"
+
+namespace bamg {
+
+	class Mesh;
+	class BamgVertex;
+	class Triangle;
+
+	class Triangle {
+
+		friend class AdjacentTriangle;
+
+		private:
+			BamgVertex *vertices[3];        // 3 vertices if t is triangle, t[i] allowed by access function, (*t)[i] if pointer
+			Triangle   *adj[3];             // 3 pointers toward the adjacent triangles
+			short       AdjEdgeIndex[3];   // edge id in the adjacent triangles. The edge number 1 is the edge number AdjEdgeIndex[1] in the Adjacent triangle 1
+
+		public: 
+			Icoor2 det; //Integer determinant (twice its area)
+			union { 
+				Triangle *link;
+				long      color;
+			};
+
+			//Constructors/Destructors
+			Triangle();
+			Triangle(Mesh *Th,long i,long j,long k);
+			Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2);
+
+			//Operators
+			const BamgVertex & operator[](int i) const {return *vertices[i];};
+			BamgVertex & operator[](int i)  {return *vertices[i];};
+			const BamgVertex * operator()(int i) const {return vertices[i];};
+			BamgVertex * & operator()(int i)  {return vertices[i];};
+
+			//Methods
+			void              Echo();
+			double            Anisotropy() const;
+			double            Length() const;
+			int               swap(short a1,int=0);
+			long              Optim(short a,int =0);
+			int               Locked(int a)const;
+			int               Hidden(int a)const;
+			int               GetAllflag(int a);
+			void              SetAllFlag(int a,int f);
+			double            QualityQuad(int a,int option=1) const;
+			short             NuEdgeTriangleAdj(int i) const;
+			AdjacentTriangle  FindBoundaryEdge(int  i) const;
+			AdjacentTriangle  Adj(int i) const;
+			Triangle         *TriangleAdj(int i) const;
+			Triangle         *Quadrangle(BamgVertex  *& v0,BamgVertex *& v1,BamgVertex *& v2,BamgVertex *& v3) const;
+			void              Renumbering(Triangle   *tb,Triangle *te, long *renu);
+			void              Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu);
+			void              SetAdjAdj(short a);
+			void              SetAdj2(short a,Triangle *t,short aat);
+			void              SetSingleVertexToTriangleConnectivity();
+			void              SetHidden(int a);
+			void              SetLocked(int a);
+			void              SetMarkUnSwap(int a);
+			void              SetUnMarkUnSwap(int a);
+			void              SetDet();
+
+			//Inline methods
+			double qualite() ;
+			void  Set(const Triangle &,const Mesh &,Mesh &);
+			int   In(BamgVertex *v) const { return vertices[0]==v || vertices[1]==v || vertices[2]==v ;}
+
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/VertexOnEdge.cpp
===================================================================
--- /issm/trunk/src/c/bamg/VertexOnEdge.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/VertexOnEdge.cpp	(revision 15396)
@@ -0,0 +1,25 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnEdge.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Methods*/
+	/*FUNCTION VertexOnEdge::Set {{{*/
+	void VertexOnEdge::Set(const Mesh & Th ,long i,Mesh & ThNew){
+		*this = Th.VertexOnBThEdge[i];  
+		v = ThNew.vertices + Th.GetId(v);
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnEdge::SetOnBTh{{{*/
+	void VertexOnEdge::SetOnBTh(){
+		v->BackgroundEdgeHook=this;
+		v->IndexInTriangle=IsVertexOnEdge;  
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/VertexOnEdge.h
===================================================================
--- /issm/trunk/src/c/bamg/VertexOnEdge.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/VertexOnEdge.h	(revision 15396)
@@ -0,0 +1,35 @@
+#ifndef _VERTEXONEDGE_H_
+#define _VERTEXONEDGE_H_
+
+#include "./include.h"
+#include "./Edge.h"
+
+namespace bamg {
+
+	class Mesh;
+	class BamgVertex;
+
+	class VertexOnEdge {
+
+		public:
+			BamgVertex* v;
+			Edge*   be;
+			double abcisse;
+
+			//Constructors
+			VertexOnEdge(BamgVertex * w, Edge *bw,double s) :v(w),be(bw),abcisse(s) {};
+			VertexOnEdge(){};
+
+			//Operators
+			operator double () const { return abcisse;}
+			operator BamgVertex* () const { return v;}  
+			operator Edge* () const { return be;}  
+			BamgVertex & operator[](int i) const { return (*be)[i];}
+
+			//Methods
+			void SetOnBTh();
+			void Set(const Mesh &,long,Mesh &);  
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/VertexOnGeom.cpp
===================================================================
--- /issm/trunk/src/c/bamg/VertexOnGeom.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/VertexOnGeom.cpp	(revision 15396)
@@ -0,0 +1,70 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnGeom.h"
+#include "Mesh.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION VertexOnGeom::VertexOnGeom(){{{*/
+	VertexOnGeom::VertexOnGeom(){
+		meshvertex=NULL;
+		curvilincoord=0;
+		gv=0;
+	} 
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomVertex &g){{{*/
+	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomVertex &g){
+		meshvertex=&m;
+		curvilincoord=-1;
+		gv=&g;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomEdge &g,double s){{{*/
+	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomEdge &g,double s){
+		meshvertex=&m;
+		curvilincoord=s;
+		ge=&g;
+	}
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION VertexOnGeom::Set {{{*/
+	void VertexOnGeom::Set(const VertexOnGeom & rec,const Mesh & Th ,Mesh & ThNew){
+		*this = rec;  
+		meshvertex = ThNew.vertices + Th.GetId(meshvertex);
+		if (gv)
+		 if (curvilincoord < 0 )
+		  gv = ThNew.Gh.vertices + Th.Gh.GetId(gv);
+		 else
+		  ge = ThNew.Gh.edges + Th.Gh.GetId(ge);
+
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::OnGeomVertex{{{*/
+	int VertexOnGeom::OnGeomVertex()const{
+		return this? curvilincoord <0 :0;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::OnGeomEdge{{{*/
+	int VertexOnGeom::OnGeomEdge() const{
+		return this? curvilincoord >=0 :0;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::IsRequiredVertex{{{*/
+	int VertexOnGeom::IsRequiredVertex() {
+		return this? ((curvilincoord<0 ? (gv?gv->Required():0):0 )) : 0;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::SetOn{{{*/
+	void VertexOnGeom::SetOn(){
+		meshvertex->GeomEdgeHook=this;
+		meshvertex->IndexInTriangle=IsVertexOnGeom;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/VertexOnGeom.h
===================================================================
--- /issm/trunk/src/c/bamg/VertexOnGeom.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/VertexOnGeom.h	(revision 15396)
@@ -0,0 +1,45 @@
+#ifndef _VERTEXONGEOM_H_
+#define _VERTEXONGEOM_H_
+
+#include "./include.h"
+#include "./GeomVertex.h"
+
+namespace bamg {
+
+	class Mesh;
+	class BamgVertex;
+	class GeomEdge;
+
+	class VertexOnGeom{
+
+		public:
+
+			BamgVertex* meshvertex;
+			double curvilincoord;  
+			union{ 
+				GeomVertex* gv; // if curvilincoord <0; 
+				GeomEdge*   ge; // if curvilincoord in [0..1]
+			};
+
+			//Constructors/Destructors
+			VertexOnGeom();
+			VertexOnGeom(BamgVertex & m,GeomVertex &g);
+			VertexOnGeom(BamgVertex & m,GeomEdge &g,double s);
+
+			//Operators
+			operator BamgVertex*() const  {return meshvertex;}
+			operator GeomVertex * () const  {return gv;}
+			operator GeomEdge * () const  {return ge;}
+			operator const double & () const {return curvilincoord;}
+
+			//Methods
+			int  OnGeomVertex()const;
+			int  OnGeomEdge() const;
+			int  IsRequiredVertex();
+			void SetOn();
+
+			//Inline methods
+			void Set(const VertexOnGeom&,const Mesh &,Mesh &);  
+	};
+}
+#endif
Index: /issm/trunk/src/c/bamg/VertexOnVertex.cpp
===================================================================
--- /issm/trunk/src/c/bamg/VertexOnVertex.cpp	(revision 15396)
+++ /issm/trunk/src/c/bamg/VertexOnVertex.cpp	(revision 15396)
@@ -0,0 +1,34 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnVertex.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION VertexOnVertex::VertexOnVertex(){{{*/
+	VertexOnVertex::VertexOnVertex() {
+		v=NULL;
+		bv=NULL;
+	};/*}}}*/
+	/*FUNCTION VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw){{{*/
+	VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw) :v(w),bv(bw){
+
+	}/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION VertexOnVertex::Set{{{*/
+	void VertexOnVertex::Set(const Mesh &Th ,long i,Mesh &ThNew) { 
+		*this = Th.VertexOnBThVertex[i];  
+		v     = ThNew.vertices + Th.GetId(v);
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnVertex::SetOnBTh{{{*/
+	void VertexOnVertex::SetOnBTh(){
+		v->BackgroundVertexHook=bv;v->IndexInTriangle=IsVertexOnVertex;
+	}/*}}}*/
+
+} 
Index: /issm/trunk/src/c/bamg/VertexOnVertex.h
===================================================================
--- /issm/trunk/src/c/bamg/VertexOnVertex.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/VertexOnVertex.h	(revision 15396)
@@ -0,0 +1,27 @@
+#ifndef _VERTEXONVERTEX_H_
+#define _VERTEXONVERTEX_H_
+
+#include "./include.h"
+#include "./BamgVertex.h"
+
+namespace bamg {
+
+	class Mesh;
+
+	class VertexOnVertex {
+
+		public:
+			BamgVertex* v;
+			BamgVertex* bv;
+
+			//Constructors
+			VertexOnVertex();
+			VertexOnVertex(BamgVertex * w,BamgVertex *bw);
+
+			//Methods
+			void SetOnBTh();
+			void Set(const Mesh &,long,Mesh &);
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/bamgobjects.h
===================================================================
--- /issm/trunk/src/c/bamg/bamgobjects.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/bamgobjects.h	(revision 15396)
@@ -0,0 +1,34 @@
+/* \file bamgobjects.h
+ * \brief: prototype header for all bamg related objects.
+ */
+
+#ifndef BAMG_OBJECTS_H_
+#define BAMG_OBJECTS_H_
+
+/*Bamg: */
+#include "./BamgOpts.h"
+#include "./BamgGeom.h"
+#include "./BamgMesh.h"
+#include "./Metric.h"
+#include "./DoubleAndInt.h"
+#include "./Direction.h"
+#include "./BamgVertex.h"
+#include "./AdjacentTriangle.h"
+#include "./Edge.h"
+#include "./GeomVertex.h"
+#include "./GeomEdge.h"
+#include "./Curve.h"
+#include "./Triangle.h"
+#include "./ListofIntersectionTriangles.h"
+#include "./GeomSubDomain.h"
+#include "./SubDomain.h"
+#include "./VertexOnGeom.h"
+#include "./VertexOnVertex.h"
+#include "./VertexOnEdge.h"
+#include "./CrackedEdge.h"
+#include "./Mesh.h"
+#include "./Geometry.h"
+#include "./BamgQuadtree.h"
+#include "./SetOfE4.h"
+
+#endif
Index: /issm/trunk/src/c/bamg/det.h
===================================================================
--- /issm/trunk/src/c/bamg/det.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/det.h	(revision 15396)
@@ -0,0 +1,15 @@
+#ifndef _BAMGDET_H_
+#define _BAMGDET_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	Icoor2 inline det(const I2 &a,const I2 & b,const I2 &c){
+		Icoor2 bax = b.x - a.x ,bay = b.y - a.y; 
+		Icoor2 cax = c.x - a.x ,cay = c.y - a.y; 
+		return  bax*cay - bay*cax;
+	}
+
+}
+#endif
Index: /issm/trunk/src/c/bamg/include.h
===================================================================
--- /issm/trunk/src/c/bamg/include.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/include.h	(revision 15396)
@@ -0,0 +1,11 @@
+/*!\file: include.h
+ * \brief prototypes for include.h
+ */ 
+
+#ifndef _INCLUDE2_H_
+#define  _INCLUDE2_H_
+
+#include "./macros.h"
+#include "./typedefs.h"
+
+#endif //ifndef _INCLUDE2_H_
Index: /issm/trunk/src/c/bamg/macros.h
===================================================================
--- /issm/trunk/src/c/bamg/macros.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/macros.h	(revision 15396)
@@ -0,0 +1,24 @@
+#ifndef _BAMGMACROS_H
+#define _BAMGMACROS_H
+
+#include "./typedefs.h"
+
+namespace bamg {
+
+	const double Pi =3.141592653589793238462643383279502884197169399375105820974944592308;
+	const float  fPi=3.141592653589793238462643383279502884197169399375105820974944592308;
+	const  int   IsVertexOnGeom = 8;
+	const  int   IsVertexOnVertex = 16;
+	const  int   IsVertexOnEdge = 32;
+	static const short VerticesOfTriangularEdge[3][2] = {{1,2},{2,0},{0,1}};
+	static const short EdgesVertexTriangle[3][2] = {{1,2},{2,0},{0,1}};
+	static const short OppositeVertex[3] = {0,1,2};
+	static const short OppositeEdge[3] =  {0,1,2};
+	static const short NextEdge[3] = {1,2,0};
+	static const short PreviousEdge[3] = {2,0,1};
+	static const short NextVertex[3] = {1,2,0};
+	static const short PreviousVertex[3] = {2,0,1};
+	const  Icoor1 MaxICoor   = 1073741823; // 2^30-1 =111...111 (29 times one)
+}
+
+#endif
Index: /issm/trunk/src/c/bamg/typedefs.h
===================================================================
--- /issm/trunk/src/c/bamg/typedefs.h	(revision 15396)
+++ /issm/trunk/src/c/bamg/typedefs.h	(revision 15396)
@@ -0,0 +1,17 @@
+#ifndef _BAMGTYPEDEFS_H
+#define _BAMGTYPEDEFS_H
+
+#include "./R2.h"
+
+namespace bamg {
+
+	/*Integer coordinates types*/
+	typedef int  Icoor1; 
+	typedef long long Icoor2;
+
+	/*I2 and R2*/
+	typedef P2<Icoor1,Icoor2>  I2;
+	typedef P2<double,double>  R2;
+}
+
+#endif
Index: sm/trunk/src/c/classes/AdolcEdf.h
===================================================================
--- /issm/trunk/src/c/classes/AdolcEdf.h	(revision 15395)
+++ 	(revision )
@@ -1,32 +1,0 @@
-/*
- * adolc_edf.h
- *
- *  Created on: Jun 26, 2012
- *      Author: utke
- */
-
-#ifndef _ADOLC_EDF_H_
-#define _ADOLC_EDF_H_
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
-
-struct Adolc_edf {
-    ext_diff_fct *myEDF_for_solverx_p;
-    Adolc_edf() : myEDF_for_solverx_p(0) {}
-    inline friend std::ostream& operator << ( ostream&, const Adolc_edf& );
-};
-
-std::ostream& operator << ( std::ostream& out, const Adolc_edf& a) {
-    out << a.myEDF_for_solverx_p;
-    return out;
-}
-
-#endif
-
-#endif
Index: /issm/trunk/src/c/classes/Constraints/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Constraints/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/classes/Constraints/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,10 @@
+# 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/Constraint.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/Constraint.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Constraints/Constraint.h	(revision 15396)
@@ -0,0 +1,26 @@
+/*!\file:  Constraint.h
+ * \brief abstract class for Constraint object
+ * This class is a place holder for constraints
+ * It is derived from Object, so DataSets can contain them.
+ */ 
+
+#ifndef _CONSTRAINT_H_
+#define _CONSTRAINT_H_
+
+/*Headers:*/
+/*{{{*/
+class Nodes;
+#include "../../datastructures/datastructures.h"
+#include "../../toolkits/toolkits.h"
+/*}}}*/
+
+class Constraint: public Object{
+
+	public: 
+
+		virtual      ~Constraint(){};
+		virtual void ConstrainNode(Nodes* nodes,Parameters* parameters)=0;
+		virtual bool InAnalysis(int analysis_type)=0;
+
+};
+#endif
Index: /issm/trunk/src/c/classes/Constraints/Constraints.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/Constraints.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Constraints/Constraints.cpp	(revision 15396)
@@ -0,0 +1,40 @@
+/*
+ * \file Constraints.cpp
+ * \brief: Implementation of Constraints class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Constraints.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+using namespace std;
+/*}}}*/
+
+/*Numerics: */
+/*FUNCTION Constraints::NumberOfConstraints{{{*/
+int Constraints::NumberOfConstraints(void){
+
+	int localconstraints;
+	int numberofconstraints;
+
+	/*Get number of local constraints*/
+	localconstraints=this->Size();
+
+	/*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
+
+	return numberofconstraints;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Constraints/Constraints.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/Constraints.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Constraints/Constraints.h	(revision 15396)
@@ -0,0 +1,35 @@
+#ifndef _CONTAINER_CONSTRAINTS_H_
+#define  _CONTAINER_CONSTRAINTS_H_
+
+/*forward declarations */
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+
+/*! \brief Declaration of Constraints class. 
+ *
+ * Declaration of Constraints class for handling Single Point Constraints (SPCs).
+ * Constraints are vector lists (Containers) of Constraint objects.
+ */ 
+class Constraints: public DataSet{
+
+	public:
+
+		/*Object constructors and destructor*/
+		/*FUNCTION Constraints::Constraints(){{{*/
+		Constraints(){
+			enum_type=ConstraintsEnum;
+			return;
+		}
+		/*}}}*/
+		/*FUNCTION Constraints::~Constraints(){{{*/
+		~Constraints(){
+			return;
+		}
+		/*}}}*/
+
+		/*numerics*/
+		int   NumberOfConstraints(void);
+
+};
+
+#endif //ifndef _CONSTRAINTS_H_
Index: /issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp	(revision 15396)
@@ -0,0 +1,131 @@
+/*!\file SpcDynamic.c
+ * \brief: implementation of the SpcDynamic 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 "./Constraint.h"
+#include "../../shared/shared.h"
+
+/*SpcDynamic constructors and destructor*/
+/*FUNCTION SpcDynamic::SpcDynamic(){{{*/
+SpcDynamic::SpcDynamic(){
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcDynamic::SpcDynamic(int spc_sid,int spc_nodeid,...){{{*/
+SpcDynamic::SpcDynamic(int spc_sid,int spc_nodeid, int spc_dof,int spc_analysis_type){
+
+	sid=spc_sid;
+	nodeid=spc_nodeid;
+	dof=spc_dof;
+	value=0;
+	analysis_type=spc_analysis_type;
+	isset=false;
+
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcDynamic::~SpcDynamic{{{*/
+SpcDynamic::~SpcDynamic(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION SpcDynamic::Echo {{{*/
+void SpcDynamic::Echo(void){
+
+	_printf_("SpcDynamic:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   value: " << value << "\n");
+	_printf_("   isset: " <<(isset?"true":"false") << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcDynamic::DeepEcho {{{*/
+void SpcDynamic::DeepEcho(void){
+
+	this->Echo();
+	return;
+}		
+/*}}}*/
+/*FUNCTION SpcDynamic::Id {{{*/
+int    SpcDynamic::Id(void){ return sid; }
+/*}}}*/
+/*FUNCTION SpcDynamic::ObjectEnum{{{*/
+int SpcDynamic::ObjectEnum(void){
+
+	return SpcDynamicEnum;
+
+}
+/*}}}*/
+/*FUNCTION SpcDynamic::copy {{{*/
+Object* SpcDynamic::copy() {
+	return new SpcDynamic(*this); 
+}
+/*}}}*/
+
+/*Constraint virtual functions definitions: */
+/*FUNCTION SpcDynamic::InAnalysis{{{*/
+bool SpcDynamic::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+/*FUNCTION SpcDynamic::ConstrainNode{{{*/
+void SpcDynamic::ConstrainNode(Nodes* nodes,Parameters* parameters){
+
+	Node* node=NULL;
+
+	/*Chase through nodes and find the node to which this SpcDynamic applys: */
+	node=(Node*)nodes->GetObjectById(NULL,nodeid);
+
+	/*Apply constraint: */
+	if(node){ //in case the spc is dealing with a node on another cpu
+
+		/*We should first check that the value has been set... (test306)*/
+		node->ApplyConstraint(dof,value);
+	}
+}
+/*}}}*/
+
+/*SpcDynamic functions*/
+/*FUNCTION SpcDynamic::GetDof {{{*/
+int SpcDynamic::GetDof(){
+	return dof;
+}
+/*}}}*/
+/*FUNCTION SpcDynamic::GetNodeId {{{*/
+int   SpcDynamic::GetNodeId(){
+
+	return nodeid;
+}
+/*}}}*/
+/*FUNCTION SpcDynamic::GetValue {{{*/
+IssmDouble SpcDynamic::GetValue(){
+	_assert_(this->isset);
+	_assert_(!xIsNan<IssmDouble>(value));
+	return value;
+}
+/*}}}*/
+/*FUNCTION SpcDynamic::SetDynamicConstraint {{{*/
+void SpcDynamic::SetDynamicConstraint(Nodes* nodes,IssmDouble* yg_serial){
+
+	int pos;
+
+	Node* node=(Node*)nodes->GetObjectById(NULL,nodeid);
+	pos=node->GetDof(dof-1,GsetEnum);
+
+	this->value=yg_serial[pos];
+	this->isset=true;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Constraints/SpcDynamic.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcDynamic.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Constraints/SpcDynamic.h	(revision 15396)
@@ -0,0 +1,50 @@
+/*!\file SpcDynamic.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCDynamic_H_
+#define _SPCDynamic_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+/*}}}*/
+
+class SpcDynamic: public Constraint{
+
+	private: 
+		int	sid; /*! id, to track it*/
+		int	nodeid; /*!node id*/
+		int dof; /*!component*/
+		IssmDouble value; /*value*/
+		bool isset;
+		int analysis_type;
+
+	public:
+
+		/*SpcDynamic constructors, destructors:{{{*/
+		SpcDynamic();
+		SpcDynamic(int sid,int nodeid, int dof,int analysis_type);
+		~SpcDynamic();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Constraint virtual functions definitions: {{{*/
+		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool   InAnalysis(int analysis_type);
+		/*}}}*/
+		/*SpcDynamic management:{{{ */
+		int    GetNodeId();
+		int    GetDof();
+		IssmDouble GetValue();
+		void   SetDynamicConstraint(Nodes* nodes,IssmDouble *yg_serial);
+		/*}}}*/
+
+};
+
+#endif  /* _SPCStatic_H_*/
Index: /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp	(revision 15396)
@@ -0,0 +1,119 @@
+/*!\file SpcStatic.c
+ * \brief: implementation of the SpcStatic 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 "./Constraint.h"
+#include "../../shared/shared.h"
+
+/*SpcStatic constructors and destructor*/
+/*FUNCTION SpcStatic::SpcStatic(){{{*/
+SpcStatic::SpcStatic(){
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcStatic::SpcStatic(int spc_sid,int spc_nodeid,...){{{*/
+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;
+
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcStatic::~SpcStatic{{{*/
+SpcStatic::~SpcStatic(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION SpcStatic::Echo {{{*/
+void SpcStatic::Echo(void){
+
+	_printf_("SpcStatic:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   value: " << value << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcStatic::DeepEcho {{{*/
+void SpcStatic::DeepEcho(void){
+
+	_printf_("SpcStatic:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   value: " << value << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	return;
+}		
+/*}}}*/
+/*FUNCTION SpcStatic::Id {{{*/
+int    SpcStatic::Id(void){ return sid; }
+/*}}}*/
+/*FUNCTION SpcStatic::ObjectEnum{{{*/
+int SpcStatic::ObjectEnum(void){
+
+	return SpcStaticEnum;
+
+}
+/*}}}*/
+/*FUNCTION SpcStatic::copy {{{*/
+Object* SpcStatic::copy() {
+	return new SpcStatic(*this); 
+}
+/*}}}*/
+
+/*Constraint virtual functions definitions: */
+/*FUNCTION SpcStatic::InAnalysis{{{*/
+bool SpcStatic::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+/*FUNCTION SpcStatic::ConstrainNode{{{*/
+void SpcStatic::ConstrainNode(Nodes* nodes,Parameters* parameters){
+
+	Node* node=NULL;
+
+	/*Chase through nodes and find the node to which this SpcStatic applys: */
+	node=(Node*)nodes->GetObjectById(NULL,nodeid);
+
+	/*Apply constraint: */
+	if(node){ //in case the spc is dealing with a node on another cpu
+		node->ApplyConstraint(dof,value);
+	}
+}
+/*}}}*/
+
+/*SpcStatic functions*/
+/*FUNCTION SpcStatic::GetDof {{{*/
+int SpcStatic::GetDof(){
+	return dof;
+}
+/*}}}*/
+/*FUNCTION SpcStatic::GetNodeId {{{*/
+int   SpcStatic::GetNodeId(){
+
+	return nodeid;
+}
+/*}}}*/
+/*FUNCTION SpcStatic::GetValue {{{*/
+IssmDouble SpcStatic::GetValue(){
+	_assert_(!xIsNan<IssmDouble>(value));
+	return value;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Constraints/SpcStatic.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcStatic.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Constraints/SpcStatic.h	(revision 15396)
@@ -0,0 +1,48 @@
+/*!\file SpcStatic.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCStatic_H_
+#define _SPCStatic_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+/*}}}*/
+
+class SpcStatic: public Constraint{
+
+	private: 
+		int	sid; /*! id, to track it*/
+		int	nodeid; /*!node id*/
+		int dof; /*!component*/
+		IssmDouble value; /*value*/
+		int analysis_type;
+
+	public:
+
+		/*SpcStatic constructors, destructors:{{{*/
+		SpcStatic();
+		SpcStatic(int sid,int nodeid, int dof,IssmDouble value,int analysis_type);
+		~SpcStatic();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Constraint virtual functions definitions: {{{*/
+		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool   InAnalysis(int analysis_type);
+		/*}}}*/
+		/*SpcStatic management:{{{ */
+		int    GetNodeId();
+		int    GetDof();
+		IssmDouble GetValue();
+		/*}}}*/
+
+};
+
+#endif  /* _SPCStatic_H_*/
Index: /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp	(revision 15396)
@@ -0,0 +1,165 @@
+/*!\file SpcTransient.c
+ * \brief: implementation of the SpcTransient 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 "./Constraint.h"
+#include "shared/shared.h"
+
+/*SpcTransient constructors and destructor*/
+/*FUNCTION SpcTransient::SpcTransient(){{{*/
+SpcTransient::SpcTransient(){
+	sid=-1;
+	nodeid=-1;
+	dof=-1;
+	values=NULL;
+	times=NULL;
+	nsteps=-1;
+	analysis_type=-1;
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcTransient::SpcTransient(int spc_sid,int spc_nodeid,...){{{*/
+SpcTransient::SpcTransient(int spc_sid,int spc_nodeid, int spc_dof,int spc_nsteps, IssmDouble* spc_times, IssmDouble* spc_values,int spc_analysis_type){
+
+	sid=spc_sid;
+	nodeid=spc_nodeid;
+	dof=spc_dof;
+	nsteps=spc_nsteps;
+	if(spc_nsteps){
+		values=xNew<IssmDouble>(spc_nsteps);
+		times=xNew<IssmDouble>(spc_nsteps);
+		xMemCpy<IssmDouble>(values,spc_values,nsteps);
+		xMemCpy<IssmDouble>(times,spc_times,nsteps);
+	}
+	analysis_type=spc_analysis_type;
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcTransient::~SpcTransient{{{*/
+SpcTransient::~SpcTransient(){
+	xDelete<IssmDouble>(times);
+	xDelete<IssmDouble>(values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION SpcTransient::Echo {{{*/
+void SpcTransient::Echo(void){
+
+	int i;
+	_printf_("SpcTransient:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   nsteps: " << nsteps << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   steps|times|values\n");
+	for(i=0;i<nsteps;i++){
+		_printf_(i << "-" << times[i] << ":" << values[i] << "\n");
+	}
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcTransient::DeepEcho {{{*/
+void SpcTransient::DeepEcho(void){
+	this->Echo();
+}		
+/*}}}*/
+/*FUNCTION SpcTransient::Id {{{*/
+int    SpcTransient::Id(void){ return sid; }
+/*}}}*/
+/*FUNCTION SpcTransient::ObjectEnum{{{*/
+int SpcTransient::ObjectEnum(void){
+
+	return SpcTransientEnum;
+
+}
+/*}}}*/
+/*FUNCTION SpcTransient::copy {{{*/
+Object* SpcTransient::copy() {
+	return new SpcTransient(sid,nodeid,dof,nsteps,times,values,analysis_type);
+}
+/*}}}*/
+
+/*Constraint virtual functions definitions:*/
+/*FUNCTION SpcTransient::InAnalysis{{{*/
+bool SpcTransient::InAnalysis(int in_analysis_type){
+
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+/*FUNCTION SpcTransient::ConstrainNode{{{*/
+void SpcTransient::ConstrainNode(Nodes* nodes,Parameters* parameters){
+
+	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: */
+	node=(Node*)nodes->GetObjectById(NULL,nodeid);
+
+	if(node){ //in case the spc is dealing with a node on another cpu
+
+		/*Retrieve time in parameters: */
+		parameters->FindParam(&time,TimeEnum);
+
+		/*Now, go fetch value for this time: */
+		if (time<=times[0]){
+			value=values[0];
+			found=true;
+		}
+		else if (time>=times[nsteps-1]){
+			value=values[nsteps-1];
+			found=true;
+		}
+		else{
+			for(i=0;i<nsteps-1;i++){
+				if (times[i]<=time && time<times[i+1]){
+					alpha=(time-times[i])/(times[i+1]-times[i]);
+					value=(1-alpha)*values[i]+alpha*values[i+1];
+					found=true;
+					break;
+				}
+			}
+		}
+
+		if(!found)_error_("could not find time segment for constraint");
+
+		/*Apply or relax constraint: */
+		if(xIsNan<IssmDouble>(value)){
+			node->RelaxConstraint(dof);
+		}
+		else node->ApplyConstraint(dof,value);
+	}
+}
+/*}}}*/
+
+/*SpcTransient functions*/
+/*FUNCTION SpcTransient::GetDof {{{*/
+int SpcTransient::GetDof(){
+	return dof;
+}
+/*}}}*/
+/*FUNCTION SpcTransient::GetNodeId {{{*/
+int   SpcTransient::GetNodeId(){
+
+	return nodeid;
+}
+/*}}}*/
+/*FUNCTION SpcTransient::GetValue {{{*/
+IssmDouble SpcTransient::GetValue(){
+	return values[0];
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Constraints/SpcTransient.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcTransient.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Constraints/SpcTransient.h	(revision 15396)
@@ -0,0 +1,50 @@
+/*!\file SpcTransient.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCTRANSIENT_H_
+#define _SPCTRANSIENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+/*}}}*/
+
+class SpcTransient: public Constraint{
+
+	private: 
+		int	sid; /*! id, to track it*/
+		int	nodeid; /*!node id*/
+		int dof; /*!component*/
+		IssmDouble* values; /*different values in time*/
+		IssmDouble* times; /*different time steps*/
+		int nsteps; /*number of time steps*/
+		int analysis_type;
+
+	public:
+
+		/*SpcTransient constructors, destructors:{{{*/
+		SpcTransient();
+		SpcTransient(int sid,int nodeid, int dof,int nsteps, IssmDouble* times, IssmDouble* values,int analysis_type);
+		~SpcTransient();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Constraint virtual functions definitions: {{{*/
+		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool   InAnalysis(int analysis_type);
+		/*}}}*/
+		/*SpcTransient management:{{{ */
+		int    GetNodeId();
+		int    GetDof();
+		IssmDouble GetValue();
+		/*}}}*/
+
+};
+
+#endif  /* _SPCTRANSIENT_H_ */
Index: /issm/trunk/src/c/classes/Contour.h
===================================================================
--- /issm/trunk/src/c/classes/Contour.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Contour.h	(revision 15396)
@@ -0,0 +1,92 @@
+/*!\file Contour.h
+ * \brief: header file for Contour object
+ */
+
+#ifndef _CONTOUR_H_
+#define _CONTOUR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "../datastructures/datastructures.h"
+/*}}}*/
+
+template <class doubletype>
+class Contour: public Object{
+
+	public: 
+
+		int         id;
+		int         nods;     //number of vertices in the contour
+		doubletype *x;
+		doubletype *y;
+		bool        closed;   //is this contour closed?
+
+		/*Contour constructors, destructors :*/
+		/*FUNCTION Contour() {{{*/
+		Contour(){
+			this->id     = 0;
+			this->nods   = 0;
+			this->x      = NULL;
+			this->y      = NULL;
+			this->closed = false;
+		}
+		/*}}}*/
+		/*FUNCTION Contour(int pid, int nods, doubletype* x, doubletype* y,bool closed) {{{*/
+		Contour(int pid,int pnods, doubletype* px, doubletype* py,bool pclosed){
+
+			this->id     = pid;
+			this->nods   = pnods;
+			this->closed = pclosed;
+			if(nods){
+				this->x=xNew<doubletype>(nods);
+				xMemCpy<doubletype>(this->x,px,nods);
+				this->y=xNew<doubletype>(nods);
+				xMemCpy<doubletype>(this->y,py,nods);
+			}
+		}
+		/*}}}*/
+		/*FUNCTION ~Contour() {{{*/
+		~Contour(){
+			xDelete<doubletype>(this->x);
+			xDelete<doubletype>(this->y);
+		}
+		/*}}}*/
+
+		/*Object virtual function resolutoin: */
+		/*FUNCTION Echo(){{{*/
+		void Echo(void){
+			_printf_(" Contour: " << id << "\n");
+			_printf_("    nods: " << nods << "\n");
+			_printf_("  closed: " << (closed?"true":"false") << "\n");
+			if(nods){
+				_printf_("   x , y:\n");
+				for(int i=0;i<nods;i++){
+					_printf_(i << ": " << x[i] << " | " << y[i] << "\n");
+				}
+			}
+		}
+		/*}}}*/
+		/*FUNCTION DeepEcho(){{{*/
+		void DeepEcho(void){
+			this->Echo();
+		}
+		/*}}}*/
+		/*FUNCTION Id(){{{*/
+		int Id(void){
+			return id;
+		}
+		/*}}}*/
+		/*FUNCTION ObjectEnum{{{*/
+		int ObjectEnum(void){
+			return ContourEnum;
+		}
+		/*}}}*/
+		/*FUNCTION copy {{{*/
+		Object* copy() {
+			return new Contour(*this); 
+		}
+		/*}}}*/
+};
+
+#endif  /* _CONTOUR_H_ */
Index: /issm/trunk/src/c/classes/Contours.cpp
===================================================================
--- /issm/trunk/src/c/classes/Contours.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Contours.cpp	(revision 15396)
@@ -0,0 +1,66 @@
+/*
+ * \file Contours.cpp
+ * \brief: Implementation of Contours class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Contours.h"
+#include "../shared/shared.h"
+#include "./Contour.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Contours::Contours(){{{*/
+Contours::Contours(){
+	enum_type=ContoursEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Contours::~Contours(){{{*/
+Contours::~Contours(){
+	return;
+}
+/*}}}*/
+
+/*Numerics: */
+int ExpWrite(Contours* contours,char* domainname){/*{{{*/
+
+	/*I/O: */
+	FILE* fid=NULL;
+	Contour<double>* contour = NULL;
+
+	/*open domain outline file for writing: */
+	if((fid=fopen(domainname,"w"))==NULL) _error_("could not open domain file " << domainname); 
+
+	for(int counter=0;counter<contours->Size();counter++){
+		contour=(Contour<double>*)contours->GetObjectByOffset(counter);
+
+		/*Write header: */
+		fprintf(fid,"## Name:%s\n",domainname);
+		fprintf(fid,"## Icon:0\n");
+		fprintf(fid,"# Points Count	Value\n");
+		fprintf(fid,"%u %s\n",contour->nods  ,"1.");
+		fprintf(fid,"# X pos	Y pos\n");
+
+		/*Write vertices: */
+		for(int i=0;i<contour->nods;i++){
+			fprintf(fid,"%lf\t%lf\n",contour->x[i],contour->y[i]);
+		}
+
+		/*Write blank line: */
+		if(counter<contours->Size()-1) fprintf(fid,"\n");
+	}
+
+	/*close Exp file: */
+	fclose(fid);
+
+	return 1;
+}/*}}}*/
Index: /issm/trunk/src/c/classes/Contours.h
===================================================================
--- /issm/trunk/src/c/classes/Contours.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Contours.h	(revision 15396)
@@ -0,0 +1,49 @@
+/*!\brief Declaration of Contours class.
+ */ 
+
+#ifndef _CONTAINER_CONTOURS_H_
+#define  _CONTAINER_CONTOURS_H_
+
+#include "../datastructures/datastructures.h"
+#include "./Contour.h"
+
+class Contours: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Contours();
+		~Contours();
+};
+
+/*Methods that relate to datasets: */
+int ExpWrite(Contours* contours,char* domainname);
+template <class doubletype> Contours* ExpRead(char* domainname){ /*{{{*/
+
+	/*intermediary: */
+	int                  nprof;
+	int                 *profnvertices = NULL;
+	doubletype         **pprofx        = NULL;
+	doubletype         **pprofy        = NULL;
+
+	/*output: */
+	Contours *domain = NULL;
+
+	/*If domainname is an empty string, return empty dataset*/
+	if (strcmp(domainname,"")==0){
+		nprof=0;
+	}
+	else{
+		ExpRead(&nprof,&profnvertices,&pprofx, &pprofy, NULL,domainname);
+	}
+
+	/*now create dataset of contours: */
+	domain=new Contours();
+
+	for(int i=0;i<nprof;i++){
+		domain->AddObject(new Contour<doubletype>(i,profnvertices[i],pprofx[i],pprofy[i],1));
+	}
+	return domain;
+} /*}}}*/
+
+#endif //ifndef _CONTOURS_H_
Index: /issm/trunk/src/c/classes/DependentObject.cpp
===================================================================
--- /issm/trunk/src/c/classes/DependentObject.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/DependentObject.cpp	(revision 15396)
@@ -0,0 +1,99 @@
+/*!\file DependentObject.c
+ * \brief: implementation of the DependentObject 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"
+
+/*DependentObject constructors and destructor*/
+/*FUNCTION DependentObject::DependentObject(){{{*/
+DependentObject::DependentObject(){
+	this->name=NoneEnum;
+	this->type=0;
+	this->index=-1;
+}
+/*}}}*/
+/*FUNCTION DependentObject::DependentObject(int in_name, int in_type, int in_index){{{*/
+DependentObject::DependentObject(int in_name, int in_type,int in_index){
+
+	this->name=in_name;
+	this->type=in_type;
+	this->index=in_index;
+	if(in_type!=0 && in_type!=1)_error_("cannot create an DependentObject of type " << in_type);
+	if(in_type==1)_error_("not implemented yet!");
+
+}
+/*}}}*/
+/*FUNCTION DependentObject::~DependentObject() {{{*/
+DependentObject::~DependentObject(){ //destructor
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DependentObject::Echo{{{*/
+void DependentObject::Echo(void){
+
+	_printf_("DependentObject:\n");
+	_printf_("   name: " << EnumToStringx(this->name) << "\n");
+	if(this->type==0)
+		_printf_("   type: scalar\n");
+	else if(this->type==1)
+		_printf_("   type: vertex\n");
+	else
+		_error_(" unknown type: " << this->type);
+	if(this->index>=0) _printf_("   index: " << this->index << "\n");
+}
+/*}}}*/
+/*FUNCTION DependentObject::DeepEcho{{{*/
+void DependentObject::DeepEcho(void){
+	this->Echo();
+}
+/*}}}*/
+/*FUNCTION DependentObject::Id{{{*/
+int    DependentObject::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DependentObject::ObjectEnum{{{*/
+int DependentObject::ObjectEnum(void){
+
+	return DependentObjectEnum;
+
+}
+/*}}}*/
+/*FUNCTION DependentObject::copy{{{*/
+Object* DependentObject::copy(void) { 
+	return new DependentObject(name,type,index);
+} /*}}}*/
+
+/*DependentObject methods: */
+/*FUNCTION DependentObject::NumDependents{{{*/
+int  DependentObject::NumDependents(void){
+
+	/*Branch according to the type of variable: */
+	if(type==0){ /*scalar:*/
+		return 1;
+	}
+	else if(type==1){ /* vector:*/
+		_error_("not implemented yet!");
+	}
+	else _error_("should not have a type of " << type);
+}
+/*}}}*/
+/*FUNCTION DependentObject::Responsex{{{*/
+void  DependentObject::Responsex(IssmDouble* poutput_value,FemModel* femmodel){
+
+	if(this->name==MassFluxEnum){
+
+		/*to identify the mass flux that will be computed, we need the index of the profile: */
+		femmodel->parameters->SetParam(this->index,IndexEnum);
+	}
+
+	femmodel->Responsex(poutput_value,this->name,0);
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/DependentObject.h
===================================================================
--- /issm/trunk/src/c/classes/DependentObject.h	(revision 15396)
+++ /issm/trunk/src/c/classes/DependentObject.h	(revision 15396)
@@ -0,0 +1,41 @@
+/*!\file: DependentObject.h
+ * \brief prototype for DependentObject.h
+ */ 
+
+#ifndef _DEPENDENTOBJECT_H_
+#define  _DEPENDENTOBJECT_H_
+
+/*{{{*/
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+class FemModel;
+
+class DependentObject: public Object{
+
+	public:
+
+		int name;
+		int type;  /*0: scalar, 1: vertex*/
+		int index;  /*0: scalar, 1: vertex*/
+
+		/*DependentObject constructors, destructors {{{*/
+		DependentObject();
+		DependentObject(int name, int type,int index);
+		~DependentObject();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy(void);
+		/*}}}*/
+
+		/*DependentObject methods: */
+		int  NumDependents(void);
+		void Responsex(IssmDouble* poutput_value,FemModel* femmodel);
+
+};
+#endif //ifndef _DEPENDENTOBJECT_H_
Index: /issm/trunk/src/c/classes/DofIndexing.cpp
===================================================================
--- /issm/trunk/src/c/classes/DofIndexing.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/DofIndexing.cpp	(revision 15396)
@@ -9,11 +9,13 @@
 #endif
 
-#include <stdio.h>
 #include <string.h>
-#include "./classes.h"
-#include "../EnumDefinitions/EnumDefinitions.h"
-#include "../shared/shared.h"
-#include "../Container/Container.h"
-#include "../include/include.h"
+
+#include "./DofIndexing.h"
+#include "../shared/Numerics/types.h"
+#include "../shared/Numerics/constants.h"
+#include "../shared/io/Print/Print.h"
+#include "../shared/Exceptions/exceptions.h"
+#include "../shared/MemOps/MemOps.h"
+#include "../shared/Enum/Enum.h"
 
 /*DofIndexing constructors and destructor*/
@@ -25,4 +27,5 @@
 	this->ssize    = UNDEF;
 	this->clone    = false;
+	this->active   = true;
 	this->f_set    = NULL;
 	this->s_set    = NULL;
@@ -37,5 +40,7 @@
 /*FUNCTION DofIndexing::DofIndexing(int gsize){{{*/
 DofIndexing::DofIndexing(int in_gsize){
+
 	this->Init(in_gsize,NULL);
+
 }
 /*}}}*/
@@ -43,8 +48,9 @@
 DofIndexing::DofIndexing(DofIndexing* in){ //copy constructor
 
-	this->gsize = in->gsize;
-	this->fsize = in->fsize;
-	this->ssize = in->ssize;
-	this->clone = in->clone;
+	this->gsize  = in->gsize;
+	this->fsize  = in->fsize;
+	this->ssize  = in->ssize;
+	this->clone  = in->clone;
+	this->active = in->active;
 
 	if(this->gsize>0){
@@ -93,23 +99,29 @@
 void DofIndexing::Init(int in_gsize,int* in_doftype){
 
-	this->gsize=in_gsize;
-	this->clone=false;
-
-	/*allocate: */
+	this->gsize = in_gsize;
+
+	/*At this point, assume this is not a clone (will be dealt with later)*/
+	this->clone = false;
+
+	/*memory allocation */
 	if(this->gsize>0){
-		this->f_set=xNew<bool>(this->gsize);
-		this->s_set=xNew<bool>(this->gsize);
-		this->svalues=xNew<IssmDouble>(this->gsize);
-		if(in_doftype)this->doftype=xNew<int>(this->gsize);
-		this->gdoflist=xNew<int>(this->gsize);
-	}
-
+		this->f_set    = xNew<bool>(this->gsize);
+		this->s_set    = xNew<bool>(this->gsize);
+		this->svalues  = xNew<IssmDouble>(this->gsize);
+		this->gdoflist = xNew<int>(this->gsize);
+
+		if(in_doftype)
+		 this->doftype = xNew<int>(this->gsize);
+	}
+
+	/*Assign values assuming no Dirichlet at this point*/
 	for(int i=0;i<this->gsize;i++){
-		/*assume dof is free, no constraints, no rigid body constraint: */
-		this->f_set[i]=true;
-		this->s_set[i]=false;
-		if(this->doftype)this->doftype[i]=in_doftype[i];
-		this->svalues[i]=0; //0 constraint is the default value
-		this->gdoflist[i]=UNDEF;
+		this->f_set[i]    = true;
+		this->s_set[i]    = false;
+		this->svalues[i]  = 0.;      //0 constraint is the default value
+		this->gdoflist[i] = UNDEF;
+
+		if(this->doftype)
+		 this->doftype[i]=in_doftype[i];
 	}
 }
@@ -128,6 +140,9 @@
 		this->fsize=size;
 		xDelete<int>(this->fdoflist);
-		if(this->fsize)this->fdoflist=xNew<int>(size);
-		else this->fdoflist=NULL;
+
+		if(this->fsize)
+		 this->fdoflist=xNew<int>(size);
+		else
+		 this->fdoflist=NULL;
 	}
 	else if(setenum==SsetEnum){
@@ -136,6 +151,9 @@
 		this->ssize=size;
 		xDelete<int>(this->sdoflist);
-		if(this->ssize)this->sdoflist=xNew<int>(size);
-		else this->sdoflist=NULL;
+
+		if(this->ssize)
+		 this->sdoflist=xNew<int>(size);
+		else
+		 this->sdoflist=NULL;
 	}
 	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
@@ -147,7 +165,8 @@
 void DofIndexing::Echo(void){
 
-	_printLine_("DofIndexing:");
-	_printLine_("   gsize: " << gsize);
-	_printLine_("   clone: " << clone);
+	_printf_("DofIndexing:\n");
+	_printf_("   gsize:  " << gsize << "\n");
+	_printf_("   clone:  " << clone << "\n");
+	_printf_("   active: " << active << "\n");
 }
 /*}}}*/
@@ -157,47 +176,74 @@
 	int i;
 
-	_printLine_("DofIndexing:");
-	_printLine_("   gsize: " << gsize);
-	_printLine_("   fsize: " << fsize);
-	_printLine_("   ssize: " << ssize);
-	_printLine_("   clone: " << clone);
-
-	_printLine_("   set membership: f,s sets ");
+	_printf_("DofIndexing:\n");
+	_printf_("   gsize:  " << gsize << "\n");
+	_printf_("   fsize:  " << fsize << "\n");
+	_printf_("   ssize:  " << ssize << "\n");
+	_printf_("   clone:  " << clone << "\n");
+	_printf_("   active: " << active << "\n");
+
+	_printf_("   set membership: f,s sets \n");
 	for(i=0;i<gsize;i++){
-		_printLine_("      dof " << i << ": " <<(f_set[i]?"true":"false")<< " " <<(s_set[i]?"true":"false"));
-	}
-
-	_printString_("   svalues (" << this->ssize << "): |");
+		_printf_("      dof " << i << ": " <<(f_set[i]?"true":"false")<< " " <<(s_set[i]?"true":"false") << "\n");
+	}
+
+	_printf_("   svalues (" << this->ssize << "): |");
 	for(i=0;i<this->gsize;i++){
-		if(this->s_set[i])_printString_(" " << svalues[i] << " |");
-	}
-	_printLine_("");
+		if(this->s_set[i])_printf_(" " << svalues[i] << " |");
+	}
+	_printf_("\n");
 
 	if(doftype){
-		_printString_("   doftype: |");
+		_printf_("   doftype: |");
 		for(i=0;i<gsize;i++){
-			_printString_(" " << doftype[i] << " |");
+			_printf_(" " << doftype[i] << " |");
 		}
-		_printLine_("");
-	}
-	else _printLine_("   doftype: NULL");
-
-	_printString_("   g_doflist (" << this->gsize << "): |");
+		_printf_("\n");
+	}
+	else _printf_("   doftype: NULL\n");
+
+	_printf_("   g_doflist (" << this->gsize << "): |");
 	for(i=0;i<this->gsize;i++){
-		_printString_(" " << gdoflist[i] << " |");
-	}
-	_printLine_("");
-
-	_printString_("   f_doflist (" << this->fsize << "): |");
+		_printf_(" " << gdoflist[i] << " |");
+	}
+	_printf_("\n");
+
+	_printf_("   f_doflist (" << this->fsize << "): |");
 	for(i=0;i<this->fsize;i++){
-		_printString_(" " << fdoflist[i] << " |");
-	}
-	_printLine_("");
-
-	_printString_("   s_doflist (" << this->ssize << "): |");
+		_printf_(" " << fdoflist[i] << " |");
+	}
+	_printf_("\n");
+
+	_printf_("   s_doflist (" << this->ssize << "): |");
 	for(i=0;i<this->ssize;i++){
-		_printString_(" " << sdoflist[i] << " |");
-	}
-	_printLine_("");
+		_printf_(" " << sdoflist[i] << " |");
+	}
+	_printf_("\n");
 }		
 /*}}}*/
+/*FUNCTION DofIndexing::Deactivate{{{*/
+void DofIndexing::Deactivate(void){
+	this->active = false;
+
+	/*Constrain to 0. at this point*/
+	for(int i=0;i<this->gsize;i++){
+		this->f_set[i]    = false;
+		this->s_set[i]    = true;
+		this->svalues[i]  = 0.; 
+	}
+	return;
+}
+/*}}}*/
+/*FUNCTION DofIndexing::Activate{{{*/
+void DofIndexing::Activate(void){
+	this->active = true;
+
+	/*Constrain to 0. at this point*/
+	for(int i=0;i<this->gsize;i++){
+		this->f_set[i]    = true;
+		this->s_set[i]    = false;
+		this->svalues[i]  = 0.; 
+	}
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/DofIndexing.h
===================================================================
--- /issm/trunk/src/c/classes/DofIndexing.h	(revision 15395)
+++ /issm/trunk/src/c/classes/DofIndexing.h	(revision 15396)
@@ -4,7 +4,7 @@
 
 #ifndef _DOFINDEXING_H_
-#define  _DOFINDEXING_H_
+#define _DOFINDEXING_H_
 
-#include "../include/include.h"
+#include "../shared/Numerics/types.h"
 
 class DofIndexing{
@@ -19,4 +19,5 @@
 		/*partitioning: */
 		bool clone;   //this node is replicated from another one
+		bool active;  //Is this node active or inactive (all dofs are constrained)
 
 		/*boundary conditions sets: */
@@ -48,4 +49,6 @@
 		/*DofIndexing management: {{{*/
 		DofIndexing* Spawn(int* indices, int numindices);
+		void Activate(void);
+		void Deactivate(void);
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/ElementResults/BoolElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/BoolElementResult.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/ElementResults/BoolElementResult.cpp	(revision 15396)
@@ -0,0 +1,119 @@
+/*!\file BoolElementResult.c
+ * \brief: implementation of the BoolElementResult 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"
+
+/*BoolElementResult constructors and destructor*/
+/*FUNCTION BoolElementResult::BoolElementResult(){{{*/
+BoolElementResult::BoolElementResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::BoolElementResult(int in_enum_type,IssmDouble in_value,int in_step, IssmDouble in_time){{{*/
+BoolElementResult::BoolElementResult(int in_enum_type,bool in_value,int in_step, IssmDouble in_time){
+
+	enum_type=in_enum_type;
+	value=in_value;
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::~BoolElementResult(){{{*/
+BoolElementResult::~BoolElementResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION BoolElementResult::Echo {{{*/
+void BoolElementResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::DeepEcho{{{*/
+void BoolElementResult::DeepEcho(void){
+
+	_printf_("BoolElementResult:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   value: "<<(this->value?"true":"false") << "\n");
+	_printf_("   step: " << this->step << "\n");
+	_printf_("   time: " << this->time << "\n");
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::Id{{{*/
+int    BoolElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolElementResult::ObjectEnum{{{*/
+int BoolElementResult::ObjectEnum(void){
+
+	return BoolElementResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::copy{{{*/
+Object* BoolElementResult::copy() {
+
+	return new BoolElementResult(this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*ElementResult management*/
+/*FUNCTION BoolElementResult::InstanceEnum{{{*/
+int BoolElementResult::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*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){
+	return 1;
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::PatchFill{{{*/
+void BoolElementResult::PatchFill(int row, Patch* patch){
+
+	 /*Here, we fill the result information into the patch object. First, let's remember what is in a row 
+	  * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
+	  * Here, we will supply the enum_type, step, time, interpolation and nodal_values: */
+	IssmDouble IssmDoublevalue=this->value?1:0;
+	patch->fillresultinfo(row,this->enum_type,this->step,this->time,P0Enum,&IssmDoublevalue,1);
+
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::GetVectorFromResults{{{*/
+void BoolElementResult::GetVectorFromResults(Vector<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	_error_("cannot return vector on vertices");
+} /*}}}*/
+/*FUNCTION BoolElementResult::GetElementVectorFromResults{{{*/
+void BoolElementResult::GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof){
+
+	vector->SetValue(dof,value,INS_VAL);
+} /*}}}*/
Index: /issm/trunk/src/c/classes/ElementResults/BoolElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/BoolElementResult.h	(revision 15396)
+++ /issm/trunk/src/c/classes/ElementResults/BoolElementResult.h	(revision 15396)
@@ -0,0 +1,48 @@
+/*! \file BoolElementResult.h 
+ *  \brief: header file for bool result object
+ *  A boll result object is just derived from a BoolInput object, with additional time and step information.
+ */
+
+#ifndef _BOOLELEMENTRESULT_H_
+#define _BOOLELEMENTRESULT_H_
+
+/*Headers:*/
+#include "../Inputs/Input.h"
+class Parameters;
+
+class BoolElementResult: public ElementResult{
+
+	private: 
+		int    enum_type;
+		bool   value;
+		int    step;
+		IssmDouble time;
+
+	public:
+
+		/*BoolElementResult constructors, destructors: {{{*/
+		BoolElementResult();
+		BoolElementResult(int enum_type,bool value,int step,IssmDouble time);
+		~BoolElementResult();
+		/*}}}*/
+		/*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);
+		/*}}}*/
+		/*BoolElementResult management: {{{*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vector<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof);
+		/*}}}*/
+};
+#endif  /* _BOOLELEMENTRESULT_H */
Index: /issm/trunk/src/c/classes/ElementResults/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/classes/ElementResults/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,13 @@
+# 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 15396)
+++ /issm/trunk/src/c/classes/ElementResults/DoubleElementResult.cpp	(revision 15396)
@@ -0,0 +1,118 @@
+/*!\file DoubleElementResult.c
+ * \brief: implementation of the DoubleElementResult 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"
+
+/*DoubleElementResult constructors and destructor*/
+/*FUNCTION DoubleElementResult::DoubleElementResult(){{{*/
+DoubleElementResult::DoubleElementResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::DoubleElementResult(int in_enum_type,IssmDouble in_value,int in_step, IssmDouble in_time){{{*/
+DoubleElementResult::DoubleElementResult(int in_enum_type,IssmDouble in_value,int in_step, IssmDouble in_time){
+
+	enum_type=in_enum_type;
+	value=in_value;
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::~DoubleElementResult(){{{*/
+DoubleElementResult::~DoubleElementResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleElementResult::Echo {{{*/
+void DoubleElementResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::DeepEcho{{{*/
+void DoubleElementResult::DeepEcho(void){
+
+	_printf_("DoubleElementResult:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   value: " << this->value << "\n");
+	_printf_("   step: " << this->step << "\n");
+	_printf_("   time: " << this->time << "\n");
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::Id{{{*/
+int    DoubleElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleElementResult::ObjectEnum{{{*/
+int DoubleElementResult::ObjectEnum(void){
+
+	return DoubleElementResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::copy{{{*/
+Object* DoubleElementResult::copy() {
+
+	return new DoubleElementResult(this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*ElementResult management*/
+/*FUNCTION DoubleElementResult::InstanceEnum{{{*/
+int DoubleElementResult::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*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){
+	return 1;
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::PatchFill{{{*/
+void DoubleElementResult::PatchFill(int row, Patch* patch){
+
+	 /*Here, we fill the result information into the patch object. First, let's remember what is in a row 
+	  * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
+	  * Here, we will supply the enum_type, step, time, interpolation and nodal_values: */
+	patch->fillresultinfo(row,this->enum_type,this->step,this->time,P0Enum,&this->value,1);
+
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::GetVectorFromResults{{{1*/
+void DoubleElementResult::GetVectorFromResults(Vector<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	_error_("cannot return vector on vertices");
+} /*}}}*/
+/*FUNCTION DoubleElementResult::GetElementVectorFromResults{{{1*/
+void DoubleElementResult::GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof){
+
+	vector->SetValue(dof,value,INS_VAL);
+} /*}}}*/
Index: /issm/trunk/src/c/classes/ElementResults/DoubleElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/DoubleElementResult.h	(revision 15396)
+++ /issm/trunk/src/c/classes/ElementResults/DoubleElementResult.h	(revision 15396)
@@ -0,0 +1,48 @@
+/*! \file DoubleElementResult.h 
+ *  \brief: header file for IssmDouble result object
+ *  A IssmDouble result object is just derived from a DoubleInput object, with additional time and step information.
+ */
+
+#ifndef _DOUBLEELEMENTRESULT_H_
+#define _DOUBLEELEMENTRESULT_H_
+
+/*Headers:*/
+#include "../Inputs/Input.h"
+class Parameters;
+
+class DoubleElementResult: public ElementResult{
+
+	private: 
+		int    enum_type;
+		IssmDouble value;
+		int    step;
+		IssmDouble time;
+
+	public:
+
+		/*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* 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();
+		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 15396)
+++ /issm/trunk/src/c/classes/ElementResults/ElementResult.h	(revision 15396)
@@ -0,0 +1,29 @@
+/*!\file:  ElementResult.h
+ * \brief abstract class for ElementResult object
+ */ 
+
+#ifndef _ELEMENTRESULT_H_
+#define _ELEMENTRESULT_H_
+
+/*Headers:*/
+#include "../../datastructures/datastructures.h"
+class Patch;
+class Parameters;
+
+class ElementResult:public Object{
+
+	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;
+
+};
+
+#endif
Index: /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.cpp	(revision 15396)
@@ -0,0 +1,134 @@
+/*!\file PentaP1ElementResult.c
+ * \brief: implementation of the PentaP1ElementResult 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"
+
+/*PentaP1ElementResult constructors and destructor*/
+/*FUNCTION PentaP1ElementResult::PentaP1ElementResult(){{{*/
+PentaP1ElementResult::PentaP1ElementResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::PentaP1ElementResult(int in_enum_type,IssmDouble* in_values,int in_step, IssmDouble in_time){{{*/
+PentaP1ElementResult::PentaP1ElementResult(int in_enum_type,IssmDouble* in_values,int in_step, IssmDouble in_time){
+
+	int i;
+
+	enum_type=in_enum_type;
+	for(i=0;i<6;i++)values[i]=in_values[i];
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::~PentaP1ElementResult(){{{*/
+PentaP1ElementResult::~PentaP1ElementResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION PentaP1ElementResult::Echo {{{*/
+void PentaP1ElementResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::DeepEcho{{{*/
+void PentaP1ElementResult::DeepEcho(void){
+
+	_printf_("PentaP1ElementResult:\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");
+	_printf_("   step: " << this->step << "\n");
+	_printf_("   time: " << this->time << "\n");
+
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::Id{{{*/
+int    PentaP1ElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::ObjectEnum{{{*/
+int PentaP1ElementResult::ObjectEnum(void){
+
+	return PentaP1ElementResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::copy{{{*/
+Object* PentaP1ElementResult::copy() {
+
+	return new PentaP1ElementResult(this->enum_type,this->values,this->step,this->time);
+
+}
+/*}}}*/
+
+/*ElementResult management*/
+/*FUNCTION PentaP1ElementResult::InstanceEnum{{{*/
+int PentaP1ElementResult::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*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){
+	return 6;
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::PatchFill{{{*/
+void PentaP1ElementResult::PatchFill(int row, Patch* patch){
+
+	 /*Here, we fill the result information into the patch object. First, let's remember what is in a row 
+	  * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
+	  * Here, we will supply the enum_type, step, time, interpolation and nodal_values: */
+	patch->fillresultinfo(row,this->enum_type,this->step,this->time,P1Enum,this->values,6);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::GetVectorFromResults{{{*/
+void PentaP1ElementResult::GetVectorFromResults(Vector<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	IssmDouble data[6];
+
+	if(numdofs!=6)_error_("Result " << EnumToStringx(this->enum_type) << " is a PentaP1ElementResult and cannot write vector of " << numdofs << " dofs");
+	for(int i=0;i<6;i++) data[i]=this->values[i]/(IssmDouble)connectivitylist[i];
+	vector->SetValues(numdofs,doflist,&data[0],ADD_VAL);
+
+} /*}}}*/
+/*FUNCTION PentaP1ElementResult::GetElementVectorFromResults{{{*/
+void PentaP1ElementResult::GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof){
+
+	_error_("Result " << EnumToStringx(enum_type) << " is a PentaP1ElementResult and should not write vector of size numberofelemenrs");
+} /*}}}*/
Index: /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.h	(revision 15396)
+++ /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.h	(revision 15396)
@@ -0,0 +1,48 @@
+/*! \file PentaP1ElementResult.h 
+ *  \brief: header file for PentaP1ElementResult object
+ *  this object is just a PentaP1Input with additional time and step info.
+ */
+
+#ifndef _PENTAP1ELEMENTRESULT_H_
+#define _PENTAP1ELEMENTRESULT_H_
+
+/*Headers:*/
+#include "../Inputs/Input.h"
+
+class PentaP1ElementResult: public ElementResult{
+
+	private: 
+		int    enum_type;
+		IssmDouble values[6];
+		int    step;
+		IssmDouble time;
+
+	public:
+
+		/*PentaP1ElementResult constructors, destructors: {{{*/
+		PentaP1ElementResult();
+		PentaP1ElementResult(int enum_type,IssmDouble* values,int step, IssmDouble time);
+		~PentaP1ElementResult();
+		/*}}}*/
+		/*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);
+		/*}}}*/
+		/*PentaP1ElementResult management: {{{*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vector<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof);
+		/*}}}*/
+
+};
+#endif  /* _PENTAP1ELEMENTRESULT_H */
Index: /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.cpp	(revision 15396)
@@ -0,0 +1,121 @@
+/*!\file TriaP1ElementResult.c
+ * \brief: implementation of the TriaP1ElementResult 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"
+
+/*TriaP1ElementResult constructors and destructor*/
+/*FUNCTION TriaP1ElementResult::TriaP1ElementResult(){{{*/
+TriaP1ElementResult::TriaP1ElementResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::TriaP1ElementResult(int in_enum_type,IssmDouble* in_values,int in_step, IssmDouble in_time){{{*/
+TriaP1ElementResult::TriaP1ElementResult(int in_enum_type,IssmDouble* in_values,int in_step, IssmDouble in_time){
+
+	enum_type=in_enum_type;
+	values[0]=in_values[0];
+	values[1]=in_values[1];
+	values[2]=in_values[2];
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::~TriaP1ElementResult(){{{*/
+TriaP1ElementResult::~TriaP1ElementResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION TriaP1ElementResult::Echo {{{*/
+void TriaP1ElementResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::DeepEcho{{{*/
+void TriaP1ElementResult::DeepEcho(void){
+
+	_printf_("TriaP1ElementResult:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   values: [" << this->values[0] << " " << this->values[1] << " " << this->values[2] << "]\n");
+	_printf_("   step: " << this->step << "\n");
+	_printf_("   time: " << this->time << "\n");
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::Id{{{*/
+int    TriaP1ElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::ObjectEnum{{{*/
+int TriaP1ElementResult::ObjectEnum(void){
+
+	return TriaP1ElementResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::copy{{{*/
+Object* TriaP1ElementResult::copy() {
+
+	return new TriaP1ElementResult(this->enum_type,this->values,this->step,this->time);
+
+}
+/*}}}*/
+
+/*ElementResult management*/
+/*FUNCTION TriaP1ElementResult::InstanceEnum{{{*/
+int TriaP1ElementResult::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*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){
+	return 3;
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::PatchFill{{{*/
+void TriaP1ElementResult::PatchFill(int row, Patch* patch){
+
+	 /*Here, we fill the result information into the patch object. First, let's remember what is in a row 
+	  * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
+	  * Here, we will supply the enum_type, step, time, interpolation and nodal_values: */
+	patch->fillresultinfo(row,this->enum_type,this->step,this->time,P1Enum,this->values,3);
+
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::GetVectorFromResults{{{*/
+void TriaP1ElementResult::GetVectorFromResults(Vector<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	IssmDouble data[3];
+
+	if(numdofs!=3)_error_("Result " << EnumToStringx(this->enum_type) << " is a TriaP1ElementResult and cannot write vector of " << numdofs << " dofs");
+	for(int i=0;i<3;i++) data[i]=this->values[i]/(IssmDouble)connectivitylist[i];
+	vector->SetValues(numdofs,doflist,&data[0],ADD_VAL);
+
+} /*}}}*/
+/*FUNCTION TriaP1ElementResult::GetElementVectorFromResults{{{*/
+void TriaP1ElementResult::GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof){
+	_error_("Result " << EnumToStringx(enum_type) << " is a TriaP1ElementResult and should not write vector of size numberofelements");
+} /*}}}*/
Index: /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.h	(revision 15396)
+++ /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.h	(revision 15396)
@@ -0,0 +1,47 @@
+/*! \file TriaP1ElementResult.h 
+ *  \brief: header file for TriaP1ElementResult object
+ */
+
+#ifndef _TRIAP1ELEMENTRESULT_H_
+#define _TRIAP1ELEMENTRESULT_H_
+
+/*Headers:*/
+#include "../Inputs/Input.h"
+
+class TriaP1ElementResult: public ElementResult{
+
+	private: 
+		int    enum_type;
+		IssmDouble values[3];
+		int    step;
+		IssmDouble time;
+
+	public:
+
+		/*TriaP1ElementResult constructors, destructors: {{{*/
+		TriaP1ElementResult();
+		TriaP1ElementResult(int enum_type,IssmDouble* values,int step,IssmDouble time);
+		~TriaP1ElementResult();
+		/*}}}*/
+		/*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);
+		/*}}}*/
+		/*TriaP1ElementResult management: {{{*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vector<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof);
+		/*}}}*/
+
+};
+#endif  /* _TRIAP1ELEMENTRESULT_H */
Index: /issm/trunk/src/c/classes/Elements/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Elements/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,15 @@
+# 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 15396)
+++ /issm/trunk/src/c/classes/Elements/Element.h	(revision 15396)
@@ -0,0 +1,144 @@
+/*!\file:  Element.h
+ * \brief abstract class for Element object
+ * This class is a place holder for the Tria and the Penta elements. 
+ * It is derived from Element, so DataSets can contain them.
+ */ 
+
+#ifndef _ELEMENT_H_
+#define _ELEMENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+#include "../Update.h"
+
+class DataSet;
+class Parameters;
+class Patch;
+class Elements;
+class Loads;
+class Node;
+class Nodes;
+class Vertices;
+class Materials;
+template <class doublematrix> class Matrix;
+template <class doubletype> class Vector;
+
+#include "../../toolkits/toolkits.h"
+/*}}}*/
+
+class Element: public Object,public Update{
+
+	public: 
+
+		virtual        ~Element(){};
+
+		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   CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>*  Kfs)=0;
+		virtual void   CreateDVector(Vector<IssmDouble>* df)=0;
+		virtual void   CreatePVector(Vector<IssmDouble>* pf)=0;
+		virtual void   CreateJacobianMatrix(Matrix<IssmDouble>* Jff)=0;
+		virtual void   GetSolutionFromInputs(Vector<IssmDouble>* solution)=0;
+		virtual int    GetNodeIndex(Node* node)=0;
+		virtual int    GetNumberOfNodes(void)=0;
+		virtual void   GetNodesSidList(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;
+		virtual void   GetInputListOnVertices(IssmDouble* pvalue,int enumtype)=0;
+		virtual void   GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue)=0;
+		virtual void   GetInputValue(IssmDouble* pvalue,Node* node,int enumtype)=0;
+
+		virtual IssmDouble SurfaceArea(void)=0;
+		virtual void   InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum)=0;
+		virtual void   ComputeBasalStress(Vector<IssmDouble>* sigma_b)=0;
+		virtual void   ComputeStrainRate(Vector<IssmDouble>* eps)=0;
+		virtual void   PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes)=0;
+		virtual void   PatchFill(int* pcount, Patch* patch)=0;
+		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   InputToResult(int enum_type,int step,IssmDouble time)=0;
+		virtual void   InputDuplicate(int original_enum,int new_enum)=0;
+		virtual void   InputCreate(IssmDouble scalar,int name,int code)=0;
+		virtual void   InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code)=0;
+		virtual void   RequestedOutput(int output_enum,int step,IssmDouble time)=0;
+
+		virtual int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum)=0;
+		virtual void   InputScale(int enum_type,IssmDouble scale_factor)=0;
+		virtual void   GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum)=0;
+		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;
+
+		#ifdef _HAVE_RESPONSES_
+		virtual void   AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part)=0;
+		virtual void   MinVel(IssmDouble* pminvel)=0;
+		virtual void   MaxVel(IssmDouble* pmaxvel)=0;
+		virtual void   MinVx(IssmDouble* pminvx)=0;
+		virtual void   MaxVx(IssmDouble* pmaxvx)=0;
+		virtual void   MaxAbsVx(IssmDouble* pmaxabsvx)=0;
+		virtual void   MinVy(IssmDouble* pminvy)=0;
+		virtual void   MaxVy(IssmDouble* pmaxvy)=0;
+		virtual void   MaxAbsVy(IssmDouble* pmaxabsvy)=0;
+		virtual void   MinVz(IssmDouble* pminvz)=0;
+		virtual void   MaxVz(IssmDouble* pmaxvz)=0;
+		virtual void   MaxAbsVz(IssmDouble* pmaxabsvz)=0;
+		virtual IssmDouble MassFlux(IssmDouble* segment)=0;
+		virtual void   ElementResponse(IssmDouble* presponse,int response_enum)=0;
+		virtual IssmDouble IceVolume(void)=0;
+		virtual IssmDouble TotalSmb(void)=0;
+		#endif
+
+		#ifdef _HAVE_GIA_
+		virtual void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y)=0;
+		#endif
+
+		#ifdef _HAVE_CONTROL_
+		virtual void   Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index)=0;
+		virtual IssmDouble ThicknessAbsMisfit(int weight_index)=0;
+		virtual IssmDouble SurfaceAbsVelMisfit(int weight_index)=0;
+		virtual IssmDouble SurfaceRelVelMisfit(int weight_index)=0;
+		virtual IssmDouble SurfaceLogVelMisfit(int weight_index)=0;
+		virtual IssmDouble SurfaceLogVxVyMisfit(int weight_index)=0;
+		virtual IssmDouble SurfaceAverageVelMisfit(int weight_index)=0;
+		virtual IssmDouble ThicknessAbsGradient(int weight_index)=0;
+		virtual IssmDouble ThicknessAlongGradient(int weight_index)=0;
+		virtual IssmDouble ThicknessAcrossGradient(int weight_index)=0;
+		virtual IssmDouble BalancethicknessMisfit(int weight_index)=0;
+		virtual IssmDouble RheologyBbarAbsGradient(int weight_index)=0;
+		virtual IssmDouble DragCoefficientAbsGradient(int weight_index)=0;
+		virtual void   ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index)=0;
+		virtual void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index)=0;
+		virtual void   ControlInputScaleGradient(int enum_type, IssmDouble scale)=0;
+		virtual void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data)=0;
+		virtual void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index)=0;
+		virtual void   InputControlUpdate(IssmDouble scalar,bool save_parameter)=0;
+		#endif
+
+		#ifdef _HAVE_HYDROLOGY_
+		virtual void GetHydrologyDCInefficientHmax(IssmDouble* ph_max, Node* innode)=0;
+		virtual void GetHydrologyTransfer(Vector<IssmDouble>* transfer)=0; 
+		virtual void HydrologyEPLGetMask(Vector<IssmDouble>* mask)=0;
+		virtual void HydrologyEPLGetActive(Vector<IssmDouble>* active)=0;
+		#endif
+		
+		#ifdef _HAVE_GROUNDINGLINE_
+		virtual void   MigrateGroundingLine(IssmDouble* old_floating_ice,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;
+		#endif
+
+};
+#endif
Index: /issm/trunk/src/c/classes/Elements/ElementHook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 15396)
@@ -0,0 +1,114 @@
+/*!\file ElementHook.c
+ * \brief: implementation of the ElementHook 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"
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION ElementHook::ElementHook(){{{*/
+ElementHook::ElementHook(){
+	numanalyses=UNDEF;
+	this->hnodes     = NULL;
+	this->hvertices  = NULL;
+	this->hmaterial  = NULL;
+	this->hmatpar    = NULL;
+	this->hneighbors = NULL;
+}
+/*}}}*/
+/*FUNCTION ElementHook::~ElementHook(){{{*/
+ElementHook::~ElementHook(){
+
+	int i;
+
+	for(i=0;i<this->numanalyses;i++){
+		if (this->hnodes[i]) delete this->hnodes[i];
+	}
+	delete [] this->hnodes;
+	delete hvertices;
+	delete hmaterial;
+	delete hmatpar;
+	delete hneighbors;
+}
+/*}}}*/
+/*FUNCTION ElementHook::ElementHook(int in_numanalyses,int element_id, int numvertices,IoModel* iomodel){{{*/
+ElementHook::ElementHook(int in_numanalyses,int element_id,int numvertices,IoModel* iomodel){
+
+	/*intermediary: */
+	int matpar_id;
+	int material_id;
+
+	/*retrieve material_id: */
+	iomodel->Constant(&matpar_id,MeshNumberofelementsEnum); matpar_id++;
+
+	/*retrieve material_id*/
+	material_id = element_id;
+
+	/*retrieve vertices ids*/
+	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]);
+	}
+
+	this->numanalyses = in_numanalyses;
+	this->hnodes      = new Hook*[in_numanalyses];
+	this->hvertices   = new Hook(&vertex_ids[0],numvertices);
+	this->hmaterial   = new Hook(&material_id,1);
+	this->hmatpar     = new Hook(&matpar_id,1);
+	this->hneighbors  = NULL;
+
+	/*Initialize hnodes as NULL*/
+	for(int i=0;i<this->numanalyses;i++){
+		this->hnodes[i]=NULL;
+	}
+
+	/*Clean up*/
+	xDelete<int>(vertex_ids);
+
+}
+/*}}}*/
+
+/*FUNCTION ElementHook::SetHookNodes{{{*/
+void ElementHook::SetHookNodes(int* node_ids,int numnodes,int analysis_counter){
+	this->hnodes[analysis_counter]= new Hook(node_ids,numnodes);
+}
+/*}}}*/
+/*FUNCTION ElementHook::InitHookNeighbors{{{*/
+void ElementHook::InitHookNeighbors(int* element_ids){
+	this->hneighbors=new Hook(element_ids,2);
+}
+/*}}}*/
+/*FUNCTION ElementHook::SpawnTriaHook{{{*/
+void ElementHook::SpawnTriaHook(ElementHook* triahook,int* indices){
+
+	int i;
+	int zero=0;
+
+	triahook->numanalyses=this->numanalyses;
+	triahook->hnodes=new Hook*[this->numanalyses];
+
+	for(i=0;i<this->numanalyses;i++){
+		/*Do not do anything if Hook is empty*/
+		if (!this->hnodes[i] || this->hnodes[i]->GetNum()==0){
+			triahook->hnodes[i]=NULL;
+		}
+		else{
+			/*Else, spawn Hook*/
+			triahook->hnodes[i]=this->hnodes[i]->Spawn(indices,3);
+		}
+	}
+	// do not spawn hmaterial. material will be taken care of by Penta
+	triahook->hmaterial=NULL;
+	triahook->hvertices=(Hook*)this->hvertices->Spawn(indices,3);
+	triahook->hmatpar=(Hook*)this->hmatpar->copy();
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/ElementHook.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/ElementHook.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/ElementHook.h	(revision 15396)
@@ -0,0 +1,31 @@
+/*!\file: ElementHook.h
+ * \brief prototypes for ElementHook.h
+ */ 
+
+#ifndef _ELEMENTHOOK_H_
+#define _ELEMENTHOOK_H_
+
+class Hook;
+class IoModel;
+
+class ElementHook{
+
+	public: 
+		int    numanalyses;   //number of analysis types
+		Hook **hnodes;        // set of nodes for each analysis type
+		Hook  *hvertices;     // vertices
+		Hook  *hmaterial;     // 1 ice material
+		Hook  *hmatpar;       // 1 material parameter
+		Hook  *hneighbors;    // 2 elements, first down, second up in 3d only
+
+		/*constructors, destructors*/
+		ElementHook();
+		ElementHook(int in_numanalyses,int material_id,int numvertices,IoModel* iomodel);
+		~ElementHook();
+
+		void SetHookNodes(int* node_ids,int numnodes,int analysis_counter);
+		void SpawnTriaHook(ElementHook* triahook,int* indices);    //3d only
+		void InitHookNeighbors(int* element_ids);               //3d only
+};
+
+#endif //ifndef _ELEMENTHOOK_H_
Index: /issm/trunk/src/c/classes/Elements/Elements.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Elements.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/Elements.cpp	(revision 15396)
@@ -0,0 +1,333 @@
+/*
+ * \file Elements.cpp
+ * \brief: Implementation of Elements class, derived from DataSet class
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Element.h"
+#include "./Elements.h"
+#include "../Params/Parameters.h"
+#include "../ExternalResults/Results.h"
+#include "../ExternalResults/GenericExternalResult.h"
+#include "../Patch.h"
+#include "../../toolkits/toolkits.h"
+#include "../../shared/shared.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Elements::Elements(){{{*/
+Elements::Elements(){
+	enum_type=MeshElementsEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Elements::~Elements(){{{*/
+Elements::~Elements(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Elements::Configure{{{*/
+void Elements::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+
+	vector<Object*>::iterator object;
+	Element* element=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		element=dynamic_cast<Element*>((*object));
+		element->Configure(elements,loads,nodes,vertices,materials,parameters);
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION Elements::DeleteResults{{{*/
+void Elements::DeleteResults(void){
+
+	for (int i=0;i<this->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
+		element->DeleteResults();
+	}
+}
+/*}}}*/
+/*FUNCTION Elements::ResultsToPatch{{{*/
+Patch* Elements::ResultsToPatch(void){ 
+
+	/*output: */
+	Patch* patch=NULL;
+
+	/*intermediary: */
+	int i;
+	int count;
+	int numrows;
+	int numvertices;
+	int numnodes;
+	int max_numvertices;
+	int max_numnodes;
+	int element_numvertices;
+	int element_numrows;
+	int element_numnodes;
+
+	/*We are going to extract from the results within the elements, the desired results , and create a table 
+	 * of patch information, that will hold, for each element that computed the result that 
+	 * we desire, the enum_type of the result, the step and time, the id of the element, the interpolation type, the vertices ids, and the values 
+	 * at the nodes (could be different from the vertices). This will be used for visualization purposes. 
+	 * For example, we could build the following patch table, for velocities: 
+	 * 
+	 1. on a Beam element, Vx, at step 1, time .5, element id 1, interpolation type P0 (constant), vertices ids 1 and 2, one constant value 4.5
+	 VxEnum 1  .5  1 P0  1 2       4.5 NaN  NaN
+	 2. on a Tria element, Vz, at step 2, time .8, element id 2, interpolation type P1 (linear), vertices ids 1 3 and 4, with values at 3 nodes 4.5, 3.2, 2.5
+	 VzEnum 2  .8  2 P1  1 3 4     4.5 3.2  2.5
+	 * ... etc ...
+	 *
+	 * So what do we need to build the table: the maximum number of vertices included in the table, 
+	 * and the maximum number of nodal values, as well as the number of rows. Once we have that, 
+	 * we ask the elements to fill their own row in the table, by looping on the elememnts. 
+	 *
+	 * We will use the Patch object, which will store all of the information needed, and will be able 
+	 * to output itself to disk on its own. See object/Patch.h for format of this object.*/
+
+	/*First, determine maximum number of vertices, nodes, and number of results: */
+	numrows=0;
+	numvertices=0;
+	numnodes=0;
+
+	for(i=0;i<this->Size();i++){
+
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
+		element->PatchSize(&element_numrows,&element_numvertices,&element_numnodes);
+
+		numrows+=element_numrows;
+		if(element_numvertices>numvertices)numvertices=element_numvertices;
+		if(element_numnodes>numnodes)numnodes=element_numnodes;
+	}
+
+	/*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());
+	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());
+	numnodes=max_numnodes;
+	#endif
+
+	/*Ok, initialize Patch object: */
+	patch=new Patch(numrows,numvertices,numnodes);
+
+	/*Now, go through elements, and fill the Patch object: */
+	count=0;
+	for(i=0;i<this->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
+		element->PatchFill(&count,patch);
+	}
+
+	return patch;
+}
+/*}}}*/
+/*FUNCTION Elements::SetCurrentConfiguration{{{*/
+void Elements::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+
+	vector<Object*>::iterator object;
+	Element* element=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		element=dynamic_cast<Element*>((*object));
+		element->SetCurrentConfiguration(elements,loads,nodes,materials,parameters);
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION Elements::ToResults{{{*/
+void Elements::ToResults(Results* results,Parameters* parameters){
+
+	int my_rank;
+	int num_procs;
+
+	Patch               *patch              = NULL;
+	int                 *resultsenums       = NULL;
+	int                 *resultssizes       = NULL;
+	int                 *resultssteps       = NULL;
+	IssmDouble          *resultstimes       = NULL;
+	IssmDouble          *vector_serial      = NULL;
+	Vector<IssmDouble> *vector = NULL;
+	bool                io_gather;
+	bool                results_as_patches;
+	int                 numberofvertices     ,numberofelements;
+	int                 numberofresults      ,vectorsize;
+	int                 rank;
+	int                 minrank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
+
+	/*Recover parameters: */
+	parameters->FindParam(&io_gather,SettingsIoGatherEnum);
+	parameters->FindParam(&results_as_patches,SettingsResultsAsPatchesEnum);
+	parameters->FindParam(&numberofvertices,MeshNumberofverticesEnum);
+	parameters->FindParam(&numberofelements,MeshNumberofelementsEnum);
+
+	if(!results_as_patches){
+		/*No patch here, we prepare vectors*/
+
+		/*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
+
+		/*see what the first element of this partition has in stock (this is common to all partitions)*/
+		if(my_rank==minrank){
+			if(this->Size()==0) _error_("Cannot write results because there is no element??");
+			Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(0));
+			element->ListResultsInfo(&resultsenums,&resultssizes,&resultstimes,&resultssteps,&numberofresults);
+		}
+		#ifdef _HAVE_MPI_
+		MPI_Bcast(&numberofresults,1,MPI_DOUBLE,minrank,IssmComm::GetComm());
+		#endif
+
+		/*Get out if there is no results. Otherwise broadcast info*/
+		if(!numberofresults) return;
+		#ifdef _HAVE_MPI_
+		if(my_rank!=minrank){
+			resultsenums=xNew<int>(numberofresults);
+			resultssizes=xNew<int>(numberofresults);
+			resultstimes=xNew<IssmDouble>(numberofresults);
+			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
+
+		/*Loop over all results and get nodal vector*/
+		for(int i=0;i<numberofresults;i++){
+
+			/*Get vector for result number i*/
+			if(resultssizes[i]==P1Enum)      vectorsize=numberofvertices;
+			else if(resultssizes[i]==P0Enum) vectorsize=numberofelements;
+			else _error_("Unkown result size: " << EnumToStringx(resultssizes[i]));
+			vector=new Vector<IssmDouble>(vectorsize);
+
+			for(int j=0;j<this->Size();j++){
+				Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(j));
+				element->GetVectorFromResults(vector,i,resultsenums[i],resultssizes[i]);
+			}
+			vector->Assemble();
+
+			/*Serialize and add to results*/
+			vector_serial=vector->ToMPISerial();
+			if(my_rank==0){
+				/*No need to add this vector for all cpus*/
+				#ifdef _HAVE_ADOLC_
+				IssmPDouble* vector_serial_passive=xNew<IssmPDouble>(vectorsize);
+				for(int k=0;k<vectorsize;k++)vector_serial_passive[k]=reCast<IssmPDouble>(vector_serial[k]);
+				results->AddObject(new GenericExternalResult<double*>(results->Size()+1,resultsenums[i],vector_serial_passive,vectorsize,1,resultssteps[i],resultstimes[i]));
+				xDelete<IssmPDouble>(vector_serial_passive);
+				#else
+				results->AddObject(new GenericExternalResult<double*>(results->Size()+1,resultsenums[i],vector_serial,vectorsize,1,resultssteps[i],resultstimes[i]));
+				#endif
+			}
+
+			/*clean up*/
+			delete vector;
+			xDelete<IssmDouble>(vector_serial);
+		}
+	}
+	else{
+		/*create patch object out of all results in this dataset: */
+		patch=this->ResultsToPatch();
+
+		/*Gather onto master cpu 0, if needed: */
+		if(io_gather)patch->Gather();
+
+		/*create result object and add to results dataset:*/
+		if (patch->maxvertices && patch->maxnodes){
+			results->AddObject(new GenericExternalResult<int>(results->Size()+1,PatchVerticesEnum,patch->maxvertices,1,0));
+			results->AddObject(new GenericExternalResult<int>(results->Size()+1,PatchNodesEnum,   patch->maxnodes,1,0));
+			#ifdef _HAVE_ADOLC_
+			IssmPDouble* values_passive=xNew<IssmPDouble>(patch->numrows*patch->numcols);
+			for(int k=0;k<(patch->numrows*patch->numcols);k++)values_passive[k]=reCast<IssmPDouble>(patch->values[k]);
+			results->AddObject(new GenericExternalResult<double*>(results->Size()+1,PatchEnum,  values_passive,patch->numrows,patch->numcols,1,0));
+			xDelete<IssmPDouble>(values_passive);
+			#else
+			results->AddObject(new GenericExternalResult<double*>(results->Size()+1,PatchEnum,  patch->values,patch->numrows,patch->numcols,1,0));
+			#endif
+		}
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(resultsenums);
+	xDelete<int>(resultssizes);
+	xDelete<int>(resultssteps);
+	xDelete<IssmDouble>(resultstimes);
+	delete patch;
+}
+/*}}}*/
+/*FUNCTION Elements::MaxNumNodes{{{*/
+int Elements::MaxNumNodes(void){
+
+	int max=0;
+	int allmax;
+	int numnodes=0;
+
+	/*Now go through all elements, and get how many nodes they own, unless they are clone nodes: */
+	for(int i=0;i<this->Size();i++){
+
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
+		numnodes=element->GetNumberOfNodes();
+		if(numnodes>max)max=numnodes;
+	}
+
+	/*Grab max of all cpus: */
+	#ifdef _HAVE_MPI_
+	MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
+	max=allmax;
+	#endif
+
+	return max;
+}
+/*}}}*/
+/*FUNCTION Elements::NumberOfElements{{{*/
+int Elements::NumberOfElements(void){
+
+	int local_nelem;
+	int numberofelements;
+
+	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
+
+	return numberofelements;
+}
+/*}}}*/
+/*FUNCTION Elements::InputDuplicate{{{*/
+void Elements::InputDuplicate(int input_enum,int output_enum){
+
+	for(int i=0;i<this->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
+		element->InputDuplicate(input_enum,output_enum);
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/Elements.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Elements.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/Elements.h	(revision 15396)
@@ -0,0 +1,38 @@
+#ifndef _CONTAINER_ELEMENTS_H_
+#define  _CONTAINER_ELEMENTS_H_
+
+/*forward declarations */
+#include "../../datastructures/datastructures.h"
+class Materials;
+class Parameters;
+class Vertices;
+class Loads;
+class Nodes;
+class Patch;
+class Results;
+
+/*! \brief Declaration of Elements class 
+ *
+ * Declaration of Elements class.  Elements are vector lists (Containers) of Element objects.
+ */ 
+class Elements: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Elements();
+		~Elements();
+
+		/*numerics*/
+		void   Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void   DeleteResults(void);
+		int    MaxNumNodes(void);
+		void   SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void   ToResults(Results* results,Parameters* parameters);
+		Patch* ResultsToPatch(void);
+		int    NumberOfElements(void);
+		void   InputDuplicate(int input_enum,int output_enum);
+
+};
+
+#endif //ifndef _ELEMENTS_H_
Index: /issm/trunk/src/c/classes/Elements/Penta.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 15396)
@@ -0,0 +1,9521 @@
+/*!\file Penta.cpp
+ * \brief: implementation of the Penta 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"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES   6
+#define NUMVERTICES2D 3
+
+/*Constructors/destructor/copy*/
+/*FUNCTION Penta::Penta(){{{*/
+Penta::Penta(){
+
+	this->nodes             = NULL;
+	this->vertices          = NULL;
+	this->material          = NULL;
+	this->matpar            = NULL;
+	this->verticalneighbors = NULL;
+	this->inputs            = NULL;
+	this->parameters        = NULL;
+	this->results           = NULL;
+	for(int i=0;i<3;i++)this->horizontalneighborsids[i]=UNDEF;
+}
+/*}}}*/
+/*FUNCTION Penta::~Penta(){{{*/
+Penta::~Penta(){
+	delete inputs;
+	delete results;
+	this->parameters=NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::Penta(int id, int index, IoModel* iomodel,int nummodels) {{{*/
+Penta::Penta(int penta_id, int penta_sid, int index, IoModel* iomodel,int nummodels)
+	:PentaRef(nummodels)
+	,ElementHook(nummodels,index+1,6,iomodel) //index+1: material id, iomodel->numberofelements+1: matpar id
+                                                                      { //i is the element index
+
+	int i;
+	int penta_elements_ids[2];
+
+	/*Checks in debugging mode*/
+	/*{{{*/
+	_assert_(iomodel->Data(MeshUpperelementsEnum));
+	_assert_(iomodel->Data(MeshLowerelementsEnum));
+	/*}}}*/
+
+	/*id: */
+	this->id=penta_id;
+	this->sid=penta_sid;
+
+	/*Build neighbors list*/
+	if (xIsNan<IssmDouble>(iomodel->Data(MeshUpperelementsEnum)[index]) || iomodel->Data(MeshUpperelementsEnum)[index]==-1.) penta_elements_ids[1]=this->id; //upper penta is the same penta
+	else                                    penta_elements_ids[1]=reCast<int,IssmDouble>((iomodel->Data(MeshUpperelementsEnum)[index]));
+	if (xIsNan<IssmDouble>(iomodel->Data(MeshLowerelementsEnum)[index]) || iomodel->Data(MeshLowerelementsEnum)[index]==-1.) penta_elements_ids[0]=this->id; //lower penta is the same penta
+	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.
+	this->parameters=NULL;
+
+	/*intialize inputs and results: */
+	this->inputs=new Inputs();
+	this->results=new Results();
+
+	/*initialize pointers:*/
+	this->nodes             = NULL;
+	this->vertices          = NULL;
+	this->material          = NULL;
+	this->matpar            = NULL;
+	this->verticalneighbors = NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::copy {{{*/
+Object* Penta::copy() {
+
+	int i;
+
+	Penta* penta=NULL;
+
+	penta=new Penta();
+
+	//deal with PentaRef mother class
+	penta->element_type_list=xNew<int>(this->numanalyses);
+	for(i=0;i<this->numanalyses;i++) penta->element_type_list[i]=this->element_type_list[i];
+
+	//deal with ElementHook
+	penta->numanalyses=this->numanalyses;
+	penta->hnodes=new Hook*[penta->numanalyses];
+	for(i=0;i<penta->numanalyses;i++)penta->hnodes[i]=(Hook*)this->hnodes[i]->copy();
+	penta->hvertices=(Hook*)this->hvertices->copy();
+	penta->hmaterial=(Hook*)this->hmaterial->copy();
+	penta->hmatpar=(Hook*)this->hmatpar->copy();
+	penta->hneighbors=(Hook*)this->hneighbors->copy();
+
+	/*deal with Penta  copy fields: */
+	penta->id=this->id;
+	penta->sid=this->sid;
+	if(this->inputs){
+		penta->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		penta->inputs=new Inputs();
+	}
+	if(this->results){
+		penta->results=(Results*)this->results->Copy();
+	}
+	else{
+		penta->results=new Results();
+	}
+	/*point parameters: */
+	penta->parameters=this->parameters;
+
+	/*recover objects: */
+	penta->nodes=xNew<Node*>(6); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+	for(i=0;i<6;i++)penta->nodes[i]=this->nodes[i];
+	penta->vertices=(Vertex**)penta->hvertices->deliverp();
+	penta->material=(Material*)penta->hmaterial->delivers();
+	penta->matpar=(Matpar*)penta->hmatpar->delivers();
+	penta->verticalneighbors=(Penta**)penta->hneighbors->deliverp();
+
+	/*neighbors: */
+	for(i=0;i<3;i++)penta->horizontalneighborsids[i]=this->horizontalneighborsids[i];
+
+	return penta;
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION Penta::BedNormal {{{*/
+void Penta::BedNormal(IssmDouble* bed_normal, IssmDouble xyz_list[3][3]){
+
+	int i;
+	IssmDouble v13[3],v23[3];
+	IssmDouble normal[3];
+	IssmDouble normal_norm;
+
+	for (i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+	normal_norm=sqrt( pow(normal[0],2)+pow(normal[1],2)+pow(normal[2],2) );
+
+	/*Bed normal is opposite to surface normal*/
+	*(bed_normal)=-normal[0]/normal_norm;
+	*(bed_normal+1)=-normal[1]/normal_norm;
+	*(bed_normal+2)=-normal[2]/normal_norm;
+}
+/*}}}*/
+/*FUNCTION Penta::BasalFrictionCreateInput {{{*/
+void Penta::BasalFrictionCreateInput(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int    count;
+	IssmDouble basalfriction[NUMVERTICES]={0,0,0,0,0,0};
+	IssmDouble alpha2,vx,vy;
+	Friction*  friction=NULL;
+	GaussPenta* gauss=NULL;
+
+	/* Basal friction can only be found at the base of an ice sheet: */
+	if (!IsOnBed() || IsFloating()){
+		//empty friction: 
+		this->inputs->AddInput(new PentaP1Input(BasalFrictionEnum,&basalfriction[0]));
+		return;
+	}
+
+	/*Retrieve all inputs and parameters*/
+	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);
+
+	/*Build friction element, needed later: */
+	friction=new Friction("3d",inputs,matpar,DiagnosticHorizAnalysisEnum);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	count=0;
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		basalfriction[count]=alpha2*(pow(vx,2.0)+pow(vy,2.0));
+		count++;
+	}
+
+	/*Create PentaVertex input, which will hold the basal friction:*/
+	this->inputs->AddInput(new PentaP1Input(BasalFrictionEnum,&basalfriction[0]));
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+}
+/*}}}*/
+/*FUNCTION Penta::ComputeBasalStress {{{*/
+void  Penta::ComputeBasalStress(Vector<IssmDouble>* sigma_b){
+
+	int         i,j;
+	int         dofv[3]={0,1,2};
+	int         dofp[1]={3};
+	int         analysis_type,approximation;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  xyz_list_tria[3][3];
+	IssmDouble  rho_ice,gravity,stokesreconditioning;
+	IssmDouble  pressure,viscosity,Jdet2d;
+	IssmDouble  bed_normal[3];
+	IssmDouble  basalforce[3];
+	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble  stresstensor[6]={0.0};
+	IssmDouble  sigma_xx,sigma_yy,sigma_zz;
+	IssmDouble  sigma_xy,sigma_xz,sigma_yz;
+	IssmDouble  surface=0,value=0;
+	GaussPenta* gauss;
+
+	/*retrive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*Check analysis_types*/
+	if (analysis_type!=DiagnosticHorizAnalysisEnum) _error_("Not supported yet!");
+	if (approximation!=StokesApproximationEnum) _error_("Not supported yet!");
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+
+	if(!IsOnBed()){
+		//put zero
+		sigma_b->SetValue(id-1,0.0,INS_VAL);
+		return;
+	}
+
+	/*recovre material parameters: */
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	for(i=0;i<3;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*Retrieve all inputs we will be needing: */
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_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: */
+	gauss=new GaussPenta(0,1,2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/*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]);
+		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_xy=2*viscosity*epsilon[3];
+		sigma_xz=2*viscosity*epsilon[4];
+		sigma_yz=2*viscosity*epsilon[5];
+
+		/*Get normal vector to the bed */
+		BedNormal(&bed_normal[0],xyz_list_tria);
+
+		/*basalforce*/
+		basalforce[0] += sigma_xx*bed_normal[0] + sigma_xy*bed_normal[1] + sigma_xz*bed_normal[2];
+		basalforce[1] += sigma_xy*bed_normal[0] + sigma_yy*bed_normal[1] + sigma_yz*bed_normal[2];
+		basalforce[2] += sigma_xz*bed_normal[0] + sigma_yz*bed_normal[1] + sigma_zz*bed_normal[2];
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		value+=sigma_zz*Jdet2d*gauss->weight;
+		surface+=Jdet2d*gauss->weight;
+	}
+	value=value/surface;
+
+	/*Add value to output*/
+	sigma_b->SetValue(id-1,value,INS_VAL);
+}
+/*}}}*/
+/*FUNCTION Penta::ComputeStrainRate {{{*/
+void  Penta::ComputeStrainRate(Vector<IssmDouble>* eps){
+
+	_error_("Not implemented yet");
+
+}
+/*}}}*/
+/*FUNCTION Penta::ComputeStressTensor {{{*/
+void  Penta::ComputeStressTensor(){
+
+	IssmDouble      xyz_list[NUMVERTICES][3];
+	IssmDouble      pressure,viscosity;
+	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble      sigma_xx[NUMVERTICES];
+	IssmDouble		sigma_yy[NUMVERTICES];
+	IssmDouble		sigma_zz[NUMVERTICES];
+	IssmDouble      sigma_xy[NUMVERTICES];
+	IssmDouble		sigma_xz[NUMVERTICES];
+	IssmDouble		sigma_yz[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_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 vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		material->GetViscosity3d(&viscosity,&epsilon[0]);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx[iv]=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
+		sigma_yy[iv]=2*viscosity*epsilon[1]-pressure;
+		sigma_zz[iv]=2*viscosity*epsilon[2]-pressure;
+		sigma_xy[iv]=2*viscosity*epsilon[3];
+		sigma_xz[iv]=2*viscosity*epsilon[4];
+		sigma_yz[iv]=2*viscosity*epsilon[5];
+	}
+
+	/*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]));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+		/*FUNCTION Penta::Configure {{{*/
+void  Penta::Configure(Elements* elementsin, Loads* loadsin, Nodes* nodesin,Vertices* verticesin, Materials* materialsin, Parameters* parametersin){
+
+	int analysis_counter;
+
+	/*go into parameters and get the analysis_counter: */
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*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: */
+	if (this->hnodes[analysis_counter]) this->hnodes[analysis_counter]->configure(nodesin);
+	this->hvertices->configure(verticesin);
+	this->hmaterial->configure(materialsin);
+	this->hmatpar->configure(materialsin);
+	this->hneighbors->configure(elementsin);
+
+	/*Now, go pick up the objects inside the hooks: */
+	if (this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+	this->vertices          = (Vertex**)this->hvertices->deliverp();
+	this->material          = (Material*)this->hmaterial->delivers();
+	this->matpar            = (Matpar*)this->hmatpar->delivers();
+	this->verticalneighbors = (Penta**)this->hneighbors->deliverp();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+	/*get inputs configured too: */
+	this->inputs->Configure(parameters);
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrix {{{*/
+void  Penta::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
+	/*}}}*/
+
+	/*Skip if water element*/
+	if(IsOnWater()) 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=CreateKMatrixDiagnosticHoriz();
+			break;
+		case AdjointHorizAnalysisEnum:
+			Ke=CreateKMatrixAdjointHoriz();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticHutter();
+			break;
+		case DiagnosticVertAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticVert();
+			break;
+		#endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			Ke=CreateBasalMassMatrix();
+			break;
+		case PrognosticAnalysisEnum:
+			Ke=CreateKMatrixPrognostic();
+			break;
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum:
+			Ke=CreateKMatrixThermal();
+			break;
+		case EnthalpyAnalysisEnum:
+			Ke=CreateKMatrixEnthalpy();
+			break;
+		case MeltingAnalysisEnum:
+			Ke=CreateKMatrixMelting();
+			break;
+		#endif
+		#ifdef _HAVE_HYDROLOGY_
+	  case HydrologyDCInefficientAnalysisEnum:
+			Ke=CreateKMatrixHydrologyDCInefficient();
+			break;
+	  case HydrologyDCEfficientAnalysisEnum:
+			Ke=CreateKMatrixHydrologyDCEfficient();
+			break;
+		#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixPrognostic {{{*/
+ElementMatrix* Penta::CreateKMatrixPrognostic(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixPrognostic();
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateBasalMassMatrix{{{*/
+ElementMatrix* Penta::CreateBasalMassMatrix(void){
+
+	if (!IsOnBed()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateMassMatrix();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateDVector {{{*/
+void  Penta::CreateDVector(Vector<IssmDouble>* df){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	ElementVector* De=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
+	/*}}}*/
+
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			De=CreateDVectorDiagnosticHoriz();
+			break;
+		#endif
+	}
+
+	/*Add to global Vector*/
+	if(De){
+		De->InsertIntoGlobal(df);
+		delete De;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVector {{{*/
+void  Penta::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*retrive parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*if debugging mode, check that all pointers exist {{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
+	/*}}}*/
+
+	/*Skip if water element*/
+	if(IsOnWater()) 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:
+			pe=CreatePVectorDiagnosticHoriz();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			pe=CreatePVectorDiagnosticHutter();
+			break;
+		case DiagnosticVertAnalysisEnum:
+			pe=CreatePVectorDiagnosticVert();
+			break;
+		#endif
+	 	#ifdef _HAVE_CONTROL_
+		case AdjointHorizAnalysisEnum:
+			pe=CreatePVectorAdjointHoriz();
+			break;
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum:
+			pe=CreatePVectorThermal();
+			break;
+		case EnthalpyAnalysisEnum:
+			pe=CreatePVectorEnthalpy();
+			break;
+		case MeltingAnalysisEnum:
+			pe=CreatePVectorMelting();
+			break;
+		#endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			pe=CreatePVectorSlope();
+			break;
+		case PrognosticAnalysisEnum:
+			pe=CreatePVectorPrognostic();
+			break;
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			pe=CreatePVectorBalancethickness();
+			break;
+		#endif
+		#ifdef _HAVE_HYDROLOGY_
+	  case HydrologyDCInefficientAnalysisEnum:
+			pe=CreatePVectorHydrologyDCInefficient();
+			break;
+	  case HydrologyDCEfficientAnalysisEnum:
+			pe=CreatePVectorHydrologyDCEfficient();
+			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 Penta::CreatePVectorPrognostic {{{*/
+ElementVector* Penta::CreatePVectorPrognostic(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorPrognostic();
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorSlope {{{*/
+ElementVector* Penta::CreatePVectorSlope(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->CreatePVectorSlope();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianMatrix{{{*/
+void  Penta::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
+	/*}}}*/
+
+	/*Skip if water element*/
+	if(IsOnWater()) 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();
+			break;
+#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Jff);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::DeepEcho{{{*/
+void Penta::DeepEcho(void){
+
+	_printf_("Penta:\n");
+	_printf_("   id: " << id << "\n");
+	nodes[0]->DeepEcho();
+	nodes[1]->DeepEcho();
+	nodes[2]->DeepEcho();
+	nodes[3]->DeepEcho();
+	nodes[4]->DeepEcho();
+	nodes[5]->DeepEcho();
+	material->DeepEcho();
+	matpar->DeepEcho();
+	_printf_("   neighbor ids: " << verticalneighbors[0]->Id() << "-" << verticalneighbors[1]->Id() << "\n");
+	_printf_("   parameters\n");
+	parameters->DeepEcho();
+	_printf_("   inputs\n");
+	inputs->DeepEcho();
+	_printf_("   results\n");
+	results->DeepEcho();
+	_printf_("neighboor sids: \n");
+	_printf_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2] << "\n");
+}
+/*}}}*/
+/*FUNCTION Penta::DeleteResults {{{*/
+void  Penta::DeleteResults(void){
+
+	/*Delete and reinitialize results*/
+	delete this->results;
+	this->results=new Results();
+
+}
+/*}}}*/
+/*FUNCTION Penta::Delta18oParameterization{{{*/
+void  Penta::Delta18oParameterization(void){
+        /*Are we on the base? If not, return*/
+        if(!IsOnBed()) return;
+
+	int        i;
+	IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+	IssmDouble TemperaturesPresentday[NUMVERTICES][12],TemperaturesLgm[NUMVERTICES][12];
+	IssmDouble PrecipitationsPresentday[NUMVERTICES][12];
+	IssmDouble tmp[NUMVERTICES];
+	IssmDouble Delta18oPresent,Delta18oLgm,Delta18oTime;
+	IssmDouble Delta18oSurfacePresent,Delta18oSurfaceLgm,Delta18oSurfaceTime;
+	IssmDouble time,yts,finaltime;
+	this->parameters->FindParam(&time,TimeEnum);
+	this->parameters->FindParam(&yts,ConstantsYtsEnum);
+	this->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+
+	/*Recover present day temperature and precipitation*/
+	Input*     input=inputs->GetInput(SurfaceforcingsTemperaturesPresentdayEnum);    _assert_(input);
+	Input*     input2=inputs->GetInput(SurfaceforcingsTemperaturesLgmEnum);          _assert_(input2);
+	Input*     input3=inputs->GetInput(SurfaceforcingsPrecipitationsPresentdayEnum); _assert_(input3);
+	GaussPenta* gauss=new GaussPenta();
+	for(int month=0;month<12;month++) {
+		for(int iv=0;iv<NUMVERTICES;iv++) {
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&TemperaturesPresentday[iv][month],gauss,month/12.*yts);
+			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
+			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
+			PrecipitationsPresentday[iv][month]=PrecipitationsPresentday[iv][month]/yts; // converion in m/sec
+		}
+	}
+
+	/*Recover delta18o and Delta18oSurface at present day, lgm and at time t*/
+	this->parameters->FindParam(&Delta18oPresent,SurfaceforcingsDelta18oEnum,finaltime);
+	this->parameters->FindParam(&Delta18oLgm,SurfaceforcingsDelta18oEnum,finaltime-(21000*yts));
+	this->parameters->FindParam(&Delta18oTime,SurfaceforcingsDelta18oEnum,time);
+	this->parameters->FindParam(&Delta18oSurfacePresent,SurfaceforcingsDelta18oSurfaceEnum,finaltime);
+	this->parameters->FindParam(&Delta18oSurfaceLgm,SurfaceforcingsDelta18oSurfaceEnum,finaltime-(21000*yts));
+	this->parameters->FindParam(&Delta18oSurfaceTime,SurfaceforcingsDelta18oSurfaceEnum,time);
+
+	/*Compute the temperature and precipitation*/
+	for(int iv=0;iv<NUMVERTICES;iv++){
+		ComputeDelta18oTemperaturePrecipitation(Delta18oSurfacePresent, Delta18oSurfaceLgm, Delta18oSurfaceTime, 
+					Delta18oPresent, Delta18oLgm, Delta18oTime,
+					&PrecipitationsPresentday[iv][0], 
+					&TemperaturesLgm[iv][0], &TemperaturesPresentday[iv][0], 
+					&monthlytemperatures[iv][0], &monthlyprec[iv][0]);
+	}
+
+	/*Update inputs*/ 
+	TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
+	TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
+	for (int imonth=0;imonth<12;imonth++) {
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
+		PentaP1Input* newmonthinput1 = new PentaP1Input(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0]);
+		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]);
+		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
+	}
+
+	this->inputs->AddInput(NewTemperatureInput);
+	this->inputs->AddInput(NewPrecipitationInput);
+
+	this->InputExtrude(SurfaceforcingsMonthlytemperaturesEnum,ElementEnum);
+	this->InputExtrude(SurfaceforcingsPrecipitationEnum,ElementEnum);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::Echo{{{*/
+
+void Penta::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Penta::ObjectEnum{{{*/
+int Penta::ObjectEnum(void){
+
+	return PentaEnum;
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetBasalElement{{{*/
+Penta* Penta::GetBasalElement(void){
+
+	/*Output*/
+	Penta* penta=NULL;
+
+	/*Go through all elements till the bed is reached*/
+	penta=this;
+	for(;;){
+		/*Stop if we have reached the surface, else, take lower penta*/
+		if (penta->IsOnBed()) break;
+
+		/* get lower Penta*/
+		penta=penta->GetLowerElement();
+		_assert_(penta->Id()!=this->id);
+	}
+
+	/*return output*/
+	return penta;
+}
+/*}}}*/
+/*FUNCTION Penta::GetDofList {{{*/
+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);
+
+	/*Populate: */
+	count=0;
+	for(i=0;i<6;i++){
+		nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
+/*FUNCTION Penta::GetGroundedPortion{{{*/
+IssmDouble Penta::GetGroundedPortion(IssmDouble* xyz_list){
+	/*Computeportion of the element that is grounded*/ 
+
+	bool               mainlyfloating = true;
+	const IssmPDouble  epsilon= 1.e-15;
+	IssmDouble         phi,s1,s2,area_init,area_grounded;
+	IssmDouble         gl[3];
+	IssmDouble         xyz_bis[3][3];
+
+	/*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
+		phi=1;
+	}
+	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
+		phi=0;
+	}
+	else{
+		/*Figure out if two nodes are floating or grounded*/
+		if(gl[0]*gl[1]*gl[2]>0) mainlyfloating=false;
+
+		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+			/*Coordinates of point 2: same as initial point 2*/
+			xyz_bis[2][0]=*(xyz_list+3*2+0);
+			xyz_bis[2][1]=*(xyz_list+3*2+1);
+			xyz_bis[2][2]=*(xyz_list+3*2+2);
+
+			/*Portion of the segments*/
+			s1=gl[2]/(gl[2]-gl[1]);
+			s2=gl[2]/(gl[2]-gl[0]);
+
+			/*New point 1*/
+			xyz_bis[1][0]=*(xyz_list+3*2+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*2+0));
+			xyz_bis[1][1]=*(xyz_list+3*2+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*2+1));
+			xyz_bis[1][2]=*(xyz_list+3*2+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*2+2));
+
+			/*New point 0*/
+			xyz_bis[0][0]=*(xyz_list+3*2+0)+s2*(*(xyz_list+3*0+0)-*(xyz_list+3*2+0));
+			xyz_bis[0][1]=*(xyz_list+3*2+1)+s2*(*(xyz_list+3*0+1)-*(xyz_list+3*2+1));
+			xyz_bis[0][2]=*(xyz_list+3*2+2)+s2*(*(xyz_list+3*0+2)-*(xyz_list+3*2+2));
+		}
+		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+			/*Coordinates of point 0: same as initial point 2*/
+			xyz_bis[0][0]=*(xyz_list+3*0+0);
+			xyz_bis[0][1]=*(xyz_list+3*0+1);
+			xyz_bis[0][2]=*(xyz_list+3*0+2);
+
+			/*Portion of the segments*/
+			s1=gl[0]/(gl[0]-gl[1]);
+			s2=gl[0]/(gl[0]-gl[2]);
+
+			/*New point 1*/
+			xyz_bis[1][0]=*(xyz_list+3*0+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*0+0));
+			xyz_bis[1][1]=*(xyz_list+3*0+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*0+1));
+			xyz_bis[1][2]=*(xyz_list+3*0+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*0+2));
+
+			/*New point 2*/
+			xyz_bis[2][0]=*(xyz_list+3*0+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*0+0));
+			xyz_bis[2][1]=*(xyz_list+3*0+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*0+1));
+			xyz_bis[2][2]=*(xyz_list+3*0+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*0+2));
+		}
+		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+			/*Coordinates of point 1: same as initial point 2*/
+			xyz_bis[1][0]=*(xyz_list+3*1+0);
+			xyz_bis[1][1]=*(xyz_list+3*1+1);
+			xyz_bis[1][2]=*(xyz_list+3*1+2);
+
+			/*Portion of the segments*/
+			s1=gl[1]/(gl[1]-gl[0]);
+			s2=gl[1]/(gl[1]-gl[2]);
+
+			/*New point 0*/
+			xyz_bis[0][0]=*(xyz_list+3*1+0)+s1*(*(xyz_list+3*0+0)-*(xyz_list+3*1+0));
+			xyz_bis[0][1]=*(xyz_list+3*1+1)+s1*(*(xyz_list+3*0+1)-*(xyz_list+3*1+1));
+			xyz_bis[0][2]=*(xyz_list+3*1+2)+s1*(*(xyz_list+3*0+2)-*(xyz_list+3*1+2));
+
+			/*New point 2*/
+			xyz_bis[2][0]=*(xyz_list+3*1+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*1+0));
+			xyz_bis[2][1]=*(xyz_list+3*1+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*1+1));
+			xyz_bis[2][2]=*(xyz_list+3*1+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*1+2));
+		}
+
+		/*Compute fraction of grounded element*/
+		GetJacobianDeterminant(&area_init, xyz_list,NULL);
+		GetJacobianDeterminant(&area_grounded, &xyz_bis[0][0],NULL);
+		if(mainlyfloating==true) area_grounded=area_init-area_grounded;
+		phi=area_grounded/area_init;
+	}
+
+	if(phi>1 || phi<0) _error_("Error. Problem with portion of grounded element: value should be between 0 and 1");
+
+	return phi;
+}
+/*}}}*/
+/*FUNCTION Penta::GetVertexPidList {{{*/
+void  Penta::GetVertexPidList(int* doflist){
+
+	for(int i=0;i<6;i++) doflist[i]=vertices[i]->Pid();
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetVertexSidList{{{*/
+void  Penta::GetVertexSidList(int* sidlist){
+
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=vertices[i]->Sid();
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetConnectivityList {{{*/
+void  Penta::GetConnectivityList(int* connectivity){
+	for(int i=0;i<NUMVERTICES;i++) connectivity[i]=nodes[i]->GetConnectivity();
+}
+/*}}}*/
+/*FUNCTION Penta::GetElementType {{{*/
+int Penta::GetElementType(){
+
+	/*return PentaRef field*/
+	return this->element_type;
+}
+/*}}}*/
+/*FUNCTION Penta::GetElementSizes{{{*/
+void Penta::GetElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){
+
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xmin,ymin,zmin;
+	IssmDouble xmax,ymax,zmax;
+
+	/*Get xyz list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	xmin=xyz_list[0][0]; xmax=xyz_list[0][0];
+	ymin=xyz_list[0][1]; ymax=xyz_list[0][1];
+	zmin=xyz_list[0][2]; zmax=xyz_list[0][2];
+
+	for(int i=1;i<NUMVERTICES;i++){
+		if(xyz_list[i][0]<xmin) xmin=xyz_list[i][0];
+		if(xyz_list[i][0]>xmax) xmax=xyz_list[i][0];
+		if(xyz_list[i][1]<ymin) ymin=xyz_list[i][1];
+		if(xyz_list[i][1]>ymax) ymax=xyz_list[i][1];
+		if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
+		if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
+	}
+
+	*hx=xmax-xmin;
+	*hy=ymax-ymin;
+	*hz=zmax-zmin;
+}
+/*}}}*/
+/*FUNCTION Penta::GetHorizontalNeighboorSids {{{*/
+int* Penta::GetHorizontalNeighboorSids(){
+
+	/*return PentaRef field*/
+	return &this->horizontalneighborsids[0];
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetLowerElement{{{*/
+Penta* Penta::GetLowerElement(void){
+
+	Penta* upper_penta=NULL;
+
+	upper_penta=(Penta*)verticalneighbors[0]; //first one (0) under, second one (1) above
+
+	return upper_penta;
+}
+/*}}}*/
+/*FUNCTION Penta::GetNodeIndex {{{*/
+int Penta::GetNodeIndex(Node* node){
+
+	_assert_(nodes);
+	for(int i=0;i<NUMVERTICES;i++){
+		if(node==nodes[i])
+		 return i;
+	}
+	_error_("Node provided not found among element nodes");
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetNodesSidList{{{*/
+void Penta::GetNodesSidList(int* sidlist){
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++){
+		sidlist[i]=nodes[i]->Sid();
+	}
+}
+/*}}}*/
+/*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");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype) {{{*/
+void Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){
+
+	/*Recover input*/
+	Input* input=inputs->GetInput(enumtype);
+	if (!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	GaussPenta *gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue) {{{*/
+void Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){
+
+	/*Recover input*/
+	Input* input=inputs->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		GaussPenta *gauss=new GaussPenta();
+		for (int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+		delete gauss;
+	}
+	else{
+		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype) {{{*/
+void Penta::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){
+
+	Input* input=inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussPenta* gauss=new GaussPenta();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::GetPhi {{{*/
+void Penta::GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity){
+	/*Compute deformational heating from epsilon and viscosity */
+
+	IssmDouble epsilon_matrix[3][3];
+	IssmDouble epsilon_eff;
+	IssmDouble epsilon_sqr[3][3];
+
+	/* Build epsilon matrix */
+	epsilon_matrix[0][0]=*(epsilon+0);
+	epsilon_matrix[1][0]=*(epsilon+3);
+	epsilon_matrix[2][0]=*(epsilon+4);
+	epsilon_matrix[0][1]=*(epsilon+3);
+	epsilon_matrix[1][1]=*(epsilon+1);
+	epsilon_matrix[2][1]=*(epsilon+5);
+	epsilon_matrix[0][2]=*(epsilon+4);
+	epsilon_matrix[1][2]=*(epsilon+5);
+	epsilon_matrix[2][2]=*(epsilon+2);
+
+	/* Effective value of epsilon_matrix */
+	epsilon_sqr[0][0]=pow(epsilon_matrix[0][0],2);
+	epsilon_sqr[1][0]=pow(epsilon_matrix[1][0],2);
+	epsilon_sqr[2][0]=pow(epsilon_matrix[2][0],2);
+	epsilon_sqr[0][1]=pow(epsilon_matrix[0][1],2);
+	epsilon_sqr[1][1]=pow(epsilon_matrix[1][1],2);
+	epsilon_sqr[2][1]=pow(epsilon_matrix[2][1],2);
+	epsilon_sqr[0][2]=pow(epsilon_matrix[0][2],2);
+	epsilon_sqr[1][2]=pow(epsilon_matrix[1][2],2);
+	epsilon_sqr[2][2]=pow(epsilon_matrix[2][2],2);
+	epsilon_eff=1/pow(2,0.5)*pow((epsilon_sqr[0][0]+epsilon_sqr[0][1]+ epsilon_sqr[0][2]+ epsilon_sqr[1][0]+ epsilon_sqr[1][1]+ epsilon_sqr[1][2]+ epsilon_sqr[2][0]+ epsilon_sqr[2][1]+ epsilon_sqr[2][2]),0.5);
+
+	/*Phi = Tr(sigma * eps) 
+	 *    = Tr(sigma'* eps)
+	 *    = 2 * eps_eff * sigma'_eff
+	 *    = 4 * mu * eps_eff ^2*/
+	*phi=4*pow(epsilon_eff,2.0)*viscosity;
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputs{{{*/
+void  Penta::GetSolutionFromInputs(Vector<IssmDouble>* solution){
+
+	int analysis_type;
+
+	/*retrive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*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:
+		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){
+			return; //the elements around will create the solution
+		}
+		break;
+	case DiagnosticHutterAnalysisEnum:
+		GetSolutionFromInputsDiagnosticHutter(solution);
+		break;
+	case DiagnosticVertAnalysisEnum:
+		//GetSolutionFromInputsDiagnosticVert(solution);
+		GetSolutionFromInputsOneDof(solution, VzEnum);
+		break;
+	#endif
+	#ifdef _HAVE_THERMAL_
+	case ThermalAnalysisEnum:
+		//GetSolutionFromInputsThermal(solution);
+		GetSolutionFromInputsOneDof(solution, TemperatureEnum);
+		break;
+	case EnthalpyAnalysisEnum:
+		//GetSolutionFromInputsEnthalpy(solution);
+		GetSolutionFromInputsOneDof(solution, EnthalpyEnum);
+		break;
+	#endif
+	#ifdef _HAVE_HYDROLOGY_
+	case HydrologyDCInefficientAnalysisEnum:
+		GetSolutionFromInputsOneDof(solution, SedimentHeadEnum);
+		break;
+	case HydrologyDCEfficientAnalysisEnum:
+		GetSolutionFromInputsOneDof(solution, EplHeadEnum);
+		break;
+  #endif
+	default:
+		_error_("analysis: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetStabilizationParameter {{{*/
+IssmDouble Penta::GetStabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){
+	/*Compute stabilization parameter*/
+	/*kappa=thermalconductivity/(rho_ice*hearcapacity) for thermal model*/
+	/*kappa=enthalpydiffusionparameter for enthalpy model*/
+
+	IssmDouble normu;
+	IssmDouble tau_parameter;
+
+	normu=pow(pow(u,2)+pow(v,2)+pow(w,2),0.5);
+	if(normu*diameter/(3*2*kappa)<1){ 
+		tau_parameter=pow(diameter,2)/(3*2*2*kappa);
+	}
+	else tau_parameter=diameter/(2*normu);
+
+	return tau_parameter;
+}
+/*}}}*/
+/*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):
+	 *
+	 * epsilon=[exx eyy exy exz eyz]
+	 *
+	 * with exz=1/2 du/dz
+	 *      eyz=1/2 dv/dz
+	 *
+	 * the contribution of vz is neglected
+	 */
+
+	int i;
+	IssmDouble epsilonvx[5];
+	IssmDouble epsilonvy[5];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetVxStrainRate3dPattyn(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3dPattyn(epsilonvy,xyz_list,gauss);
+
+	/*Sum all contributions*/
+	for(i=0;i<5;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i];
+}
+/*}}}*/
+/*FUNCTION Penta::GetStrainRate3d{{{*/
+void Penta::GetStrainRate3d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input, Input* vz_input){
+	/*Compute the 3d Strain Rate (6 components):
+	 *
+	 * epsilon=[exx eyy ezz exy exz eyz]
+	 */
+
+	int i;
+	IssmDouble epsilonvx[6];
+	IssmDouble epsilonvy[6];
+	IssmDouble epsilonvz[6];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input || !vz_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << ", vz: " << vz_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetVxStrainRate3d(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3d(epsilonvy,xyz_list,gauss);
+	vz_input->GetVzStrainRate3d(epsilonvz,xyz_list,gauss);
+
+	/*Sum all contributions*/
+	for(i=0;i<6;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i]+epsilonvz[i];
+}
+/*}}}*/
+/*FUNCTION Penta::GetUpperElement{{{*/
+Penta* Penta::GetUpperElement(void){
+
+	Penta* upper_penta=NULL;
+
+	upper_penta=(Penta*)verticalneighbors[1]; //first one under, second one above
+
+	return upper_penta;
+}
+/*}}}*/
+/*FUNCTION Penta::GetVectorFromInputs{{{*/
+void  Penta::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
+
+	int vertexpidlist[NUMVERTICES];
+
+	/*Get out if this is not an element input*/
+	if (!IsInput(input_enum)) return;
+
+	/*Prepare index list*/
+	this->GetVertexPidList(&vertexpidlist[0]);
+
+	/*Get input (either in element or material)*/
+	Input* input=inputs->GetInput(input_enum);
+	if(!input) _error_("Input " << EnumToStringx(input_enum) << " not found in element");
+
+	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+	input->GetVectorFromInputs(vector,&vertexpidlist[0]);
+}
+/*}}}*/
+/*FUNCTION Penta::GetVectorFromResults{{{*/
+void  Penta::GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int enum_in,int interp){
+
+	/*Get result*/
+	ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(offset);
+	if(elementresult->InstanceEnum()!=enum_in){
+		_error_("Results of offset "<<offset<<" is "<<EnumToStringx(elementresult->InstanceEnum())<<" when "<<EnumToStringx(enum_in)<<" was expected");
+	}  
+	if(interp==P1Enum){
+		int vertexpidlist[NUMVERTICES];
+		int connectivity[NUMVERTICES];
+		this->GetVertexSidList(&vertexpidlist[0]);
+		this->GetConnectivityList(&connectivity[0]);
+		elementresult->GetVectorFromResults(vector,&vertexpidlist[0],&connectivity[0],NUMVERTICES);
+	}
+	else if(interp==P0Enum){
+		elementresult->GetElementVectorFromResults(vector,sid);
+	}
+	else{
+		_printf_("Interpolation " << EnumToStringx(interp) << " not supported\n");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetZcoord {{{*/
+IssmDouble Penta::GetZcoord(GaussPenta* gauss){
+
+	int    i;
+	IssmDouble z;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble z_list[NUMVERTICES];
+
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	for(i=0;i<NUMVERTICES;i++) z_list[i]=xyz_list[i][2];
+	PentaRef::GetInputValue(&z,z_list,gauss);
+
+	return z;
+}
+/*}}}*/
+/*FUNCTION Penta::Sid {{{*/
+int    Penta::Sid(){
+
+	return sid;
+
+}
+/*}}}*/
+/*FUNCTION Penta::Id {{{*/
+int    Penta::Id(void){
+	return id; 
+}
+/*}}}*/
+/*FUNCTION Penta::InputArtificialNoise{{{*/
+void  Penta::InputArtificialNoise(int enum_type,IssmDouble min,IssmDouble max){
+
+	Input* input=NULL;
+
+	/*Make a copy of the original input: */
+	input=(Input*)this->inputs->GetInput(enum_type);
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+
+	/*ArtificialNoise: */
+	input->ArtificialNoise(min,max);
+}
+/*}}}*/
+/*FUNCTION Penta::InputCreate(IssmDouble scalar,int enum,int code);{{{*/
+void Penta::InputCreate(IssmDouble scalar,int name,int code){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	if ((code==5) || (code==1)){ //boolean
+		this->inputs->AddInput(new BoolInput(name,reCast<bool,IssmDouble>(scalar)));
+	}
+	else if ((code==6) || (code==2)){ //integer
+		this->inputs->AddInput(new IntInput(name,reCast<int,IssmDouble>(scalar)));
+	}
+	else if ((code==7) || (code==3)){ //IssmDouble
+		this->inputs->AddInput(new DoubleInput(name,scalar));
+	}
+	else _error_("could not recognize nature of vector from code " << code);
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputCreate(IssmDouble* vector,int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){{{*/
+void Penta::InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){//index into elements
+
+	/*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);
+
+	/*Branch on type of vector: nodal or elementary: */
+	if(vector_type==1){ //nodal vector
+
+		/*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
+		}
+
+		/*Are we in transient or static? */
+		if(M==numberofvertices){
+
+			/*create input values: */
+			for(i=0;i<6;i++)nodeinputs[i]=(IssmDouble)vector[penta_vertex_ids[i]-1];
+
+			/*create static input: */
+			this->inputs->AddInput(new PentaP1Input(vector_enum,nodeinputs));
+		}
+		else if(M==numberofvertices+1){
+			/*create transient input: */
+			for(t=0;t<N;t++){ //N is the number of times
+
+				/*create input values: */
+				for(i=0;i<6;i++){
+					row=penta_vertex_ids[i]-1;
+					nodeinputs[i]=(IssmDouble)vector[N*row+t];
+				}
+
+				/*time? :*/
+				time=(IssmDouble)vector[(M-1)*N+t]*yts;
+
+				if(t==0)transientinput=new TransientInput(vector_enum);
+				transientinput->AddTimeInput(new PentaP1Input(vector_enum,nodeinputs),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 if(vector_type==2){ //element vector
+		/*Are we in transient or static? */
+		if(M==numberofelements){
+
+			/*static mode: create an input out of the element value: */
+
+			if (code==5){ //boolean
+				this->inputs->AddInput(new BoolInput(vector_enum,reCast<bool,IssmDouble>(vector[index])));
+			}
+			else if (code==6){ //integer
+				this->inputs->AddInput(new IntInput(vector_enum,reCast<int,IssmDouble>(vector[index])));
+			}
+			else if (code==7){ //IssmDouble
+				this->inputs->AddInput(new DoubleInput(vector_enum,vector[index]));
+			}
+			else _error_("could not recognize nature of vector from code " << code);
+		}
+		else {
+			_error_("transient elementary inputs not supported yet!");
+		}
+	}
+	else{
+		_error_("Cannot add input for vector type " << vector_type << " (not supported)");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputDepthAverageAtBase{{{*/
+void  Penta::InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum){
+
+	int  step,i;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  Helem_list[NUMVERTICES];
+	IssmDouble  zeros_list[NUMVERTICES]={0.0};
+	Penta* penta=NULL;
+	Input* original_input=NULL;
+	Input* element_integrated_input=NULL;
+	Input* total_integrated_input=NULL;
+	Input* element_thickness_input=NULL;
+	Input* total_thickness_input=NULL;
+	Input* depth_averaged_input=NULL;
+
+	/*recover parameters: */
+
+	/*Are we on the base? If not, return*/
+	if(!IsOnBed()) return;
+
+	/*OK, we are on bed. Initialize global inputs as 0*/
+	total_thickness_input =new PentaP1Input(ThicknessEnum,zeros_list);
+
+	/*Now follow all the upper element from the base to the surface to integrate the input*/
+	penta=this;
+	step =0;
+	for(;;){
+
+		/*Step1: Get original input (to be depth avegaged): */
+		if (object_enum==MeshElementsEnum)
+		 original_input=(Input*)penta->inputs->GetInput(enum_type);
+		else if (object_enum==MaterialsEnum)
+		 original_input=(Input*)penta->material->inputs->GetInput(enum_type);
+		else
+		 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
+		if(!original_input) _error_("could not find input with enum " << EnumToStringx(enum_type));
+
+		/*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);
+			else if (original_input->ObjectEnum()==ControlInputEnum)
+			 total_integrated_input=new PentaP1Input(average_enum_type,zeros_list);
+			else if (original_input->ObjectEnum()==DoubleInputEnum)
+			 total_integrated_input=new DoubleInput(average_enum_type,0.0);
+			else
+			 _error_("object " << EnumToStringx(original_input->ObjectEnum()) << " not supported yet");
+		}
+
+		/*Step2: Create element thickness input*/
+		GetVerticesCoordinates(&xyz_list[0][0],penta->vertices,NUMVERTICES);
+		for(i=0;i<3;i++){
+			Helem_list[i]=xyz_list[i+3][2]-xyz_list[i][2];
+			Helem_list[i+3]=Helem_list[i];
+		}
+		element_thickness_input=new PentaP1Input(ThicknessEnum,Helem_list);
+
+		/*Step3: Vertically integrate A COPY of the original*/
+		element_integrated_input=(Input*)original_input->copy();
+		element_integrated_input->VerticallyIntegrate(element_thickness_input);
+
+		/*Add contributions to global inputs*/
+		total_integrated_input->AXPY(element_integrated_input,1.0);
+		total_thickness_input ->AXPY(element_thickness_input,1.0);
+
+		/*Clean up*/
+		delete element_thickness_input;
+		delete element_integrated_input;
+
+		/*Stop if we have reached the surface, else, take upper penta*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperElement();
+		_assert_(penta->Id()!=this->id);
+
+		/*increase couter*/
+		step++;
+	}
+
+	/*OK, now we only need to divide the depth integrated input by the total thickness!*/
+	depth_averaged_input=total_integrated_input->PointwiseDivide(total_thickness_input);
+	depth_averaged_input->ChangeEnum(average_enum_type);
+
+	/*Clean up*/
+	delete total_thickness_input;
+	delete total_integrated_input;
+
+	/*Finally, add to inputs*/
+	if (object_enum==MeshElementsEnum)
+	 this->inputs->AddInput((Input*)depth_averaged_input);
+	else if (object_enum==MaterialsEnum)
+	 this->material->inputs->AddInput((Input*)depth_averaged_input);
+	else
+	 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
+}
+/*}}}*/
+/*FUNCTION Penta::InputDuplicate{{{*/
+void  Penta::InputDuplicate(int original_enum,int new_enum){
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputExtrude {{{*/
+void  Penta::InputExtrude(int enum_type,int object_type){
+
+	int     i,num_inputs;
+	Penta  *penta       = NULL;
+	Input  *copy        = NULL;
+	Input **base_inputs = NULL;
+
+	/*Are we on the base, not on the surface?:*/
+	if(!IsOnBed()) return;
+
+	/*Step1: Get and Extrude original input: */
+	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){
+		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{
+		_error_("object of type " << EnumToStringx(object_type) << " not supported yet");
+	}
+	for(i=0;i<num_inputs;i++){
+		if(!base_inputs[i]) _error_("could not find input with enum " << EnumToStringx(enum_type) << " in object " << EnumToStringx(object_type));
+		base_inputs[i]->Extrude();
+	}
+
+	/*Stop if there is only one layer of element*/
+	if (this->IsOnSurface()) return;
+
+	/*Step 2: this input has been extruded for this element, now follow the upper element*/
+	penta=this;
+	for(;;){
+		/* get upper Penta*/
+		penta=penta->GetUpperElement();
+		_assert_(penta->Id()!=this->id);
+
+		/*Add input of the basal element to penta->inputs*/
+		for(i=0;i<num_inputs;i++){
+			copy=(Input*)base_inputs[i]->copy();
+			if (object_type==ElementEnum){
+				penta->inputs->AddInput((Input*)copy);
+			}
+			else if(object_type==MaterialsEnum){
+				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");
+			}
+		}
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+	}
+
+	/*clean-up and return*/
+	xDelete<Input*>(base_inputs);
+}
+/*}}}*/
+/*FUNCTION Penta::InputScale{{{*/
+void  Penta::InputScale(int enum_type,IssmDouble scale_factor){
+
+	Input* input=NULL;
+
+	/*Make a copy of the original input: */
+	input=(Input*)this->inputs->GetInput(enum_type);
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+
+	/*Scale: */
+	input->Scale(scale_factor);
+}
+/*}}}*/
+/*FUNCTION Penta::InputToResult{{{*/
+void  Penta::InputToResult(int enum_type,int step,IssmDouble time){
+
+	bool   found = false;
+	Input *input = NULL;
+
+	/*Go through all the input objects, and find the one corresponding to enum_type, if it exists: */
+	if (enum_type==MaterialsRheologyBbarEnum) input=this->material->inputs->GetInput(MaterialsRheologyBEnum);
+	else if (enum_type==MaterialsRheologyZbarEnum) input=this->material->inputs->GetInput(MaterialsRheologyZEnum);
+	else input=this->inputs->GetInput(enum_type);
+	//if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found in penta->inputs"); why error out? if the requested input does not exist, we should still 
+	//try and output whatever we can instead of just failing.
+	if(!input)return;
+
+	/*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));
+	#ifdef _HAVE_CONTROL_
+	if(input->ObjectEnum()==ControlInputEnum){
+		if(((ControlInput*)input)->gradient!=NULL) this->results->AddObject((Object*)((ControlInput*)input)->SpawnGradient(step,time));
+	}
+	#endif
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromConstant(bool value, int name);{{{*/
+void  Penta::InputUpdateFromConstant(bool constant, int name){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new BoolInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromConstant(IssmDouble value, int name);{{{*/
+void  Penta::InputUpdateFromConstant(IssmDouble constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new DoubleInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromConstant(int value, int name);{{{*/
+void  Penta::InputUpdateFromConstant(int constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new IntInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromIoModel {{{*/
+void Penta::InputUpdateFromIoModel(int index,IoModel* iomodel){ 
+
+	/*Intermediaries*/
+	IssmInt i,j;
+	int     penta_vertex_ids[6];
+	IssmDouble  nodeinputs[6];
+	IssmDouble  cmmininputs[6];
+	IssmDouble  cmmaxinputs[6];
+
+	IssmDouble  yts;
+	bool    control_analysis;
+	int     num_control_type;
+	int     num_cm_responses;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+	if(control_analysis) iomodel->Constant(&num_cm_responses,InversionNumCostFunctionsEnum);
+
+	/*Checks if debuging*/
+	/*{{{*/
+	_assert_(iomodel->Data(MeshElementsEnum));
+	/*}}}*/
+
+	/*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
+	}
+
+	/*Control Inputs*/
+	#ifdef _HAVE_CONTROL_
+	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+		for(i=0;i<num_control_type;i++){
+			switch(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])){
+				case BalancethicknessThickeningRateEnum:
+					if (iomodel->Data(BalancethicknessThickeningRateEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(BalancethicknessThickeningRateEnum)[penta_vertex_ids[j]-1]/yts;
+						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));
+					}
+					break;
+				case VxEnum:
+					if (iomodel->Data(VxEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(VxEnum)[penta_vertex_ids[j]-1]/yts;
+						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));
+					}
+					break;
+				case VyEnum:
+					if (iomodel->Data(VyEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(VyEnum)[penta_vertex_ids[j]-1]/yts;
+						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));
+					}
+					break;
+				case FrictionCoefficientEnum:
+					if (iomodel->Data(FrictionCoefficientEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(FrictionCoefficientEnum)[penta_vertex_ids[j]-1];
+						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));
+					}
+					break;
+				case MaterialsRheologyBbarEnum:
+				case MaterialsRheologyZbarEnum:
+					/*Material will take care of it*/ break;
+				default:
+					_error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
+			}
+		}
+	}
+	#endif
+
+	//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));
+		}
+		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]==NoneApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,NoneApproximationEnum));
+		}
+		else{
+			_error_("Approximation type " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(FlowequationElementEquationEnum)[index])) << " not supported yet");
+		}
+	}
+
+	/*DatasetInputs*/
+	if (control_analysis && iomodel->Data(InversionCostFunctionsCoefficientsEnum)) {
+
+		/*Create inputs and add to DataSetInput*/
+		DatasetInput* datasetinput=new DatasetInput(InversionCostFunctionsCoefficientsEnum);
+		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));
+		}
+
+		/*Add datasetinput to element inputs*/
+		this->inputs->AddInput(datasetinput);
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolution {{{*/
+void  Penta::InputUpdateFromSolution(IssmDouble* solution){
+
+	int analysis_type;
+
+	/*retreive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*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);
+		break;
+	case DiagnosticHutterAnalysisEnum:
+		InputUpdateFromSolutionDiagnosticHutter( solution);
+		break;
+	case DiagnosticVertAnalysisEnum:
+		InputUpdateFromSolutionDiagnosticVert( solution);
+		break;
+	#endif
+	#ifdef _HAVE_CONTROL_
+	case AdjointHorizAnalysisEnum:
+		int approximation;
+		inputs->GetInputValue(&approximation,ApproximationEnum);
+		if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+			InputUpdateFromSolutionAdjointStokes( solution);
+		}
+		else{
+			InputUpdateFromSolutionAdjointHoriz( solution);
+		}
+		break;
+	#endif
+	#ifdef _HAVE_THERMAL_
+	case ThermalAnalysisEnum:
+		InputUpdateFromSolutionThermal( solution);
+		break;
+	case EnthalpyAnalysisEnum:
+		InputUpdateFromSolutionEnthalpy( solution);
+		break;
+	case MeltingAnalysisEnum:
+		InputUpdateFromSolutionOneDof(solution,BasalforcingsMeltingRateEnum);
+		break;
+	#endif
+	case BedSlopeXAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,BedSlopeXEnum);
+		break;
+	case BedSlopeYAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,BedSlopeYEnum);
+		break;
+	case SurfaceSlopeXAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,SurfaceSlopeXEnum);
+		break;
+	case SurfaceSlopeYAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,SurfaceSlopeYEnum);
+		break;
+	case PrognosticAnalysisEnum:
+		InputUpdateFromSolutionPrognostic(solution);
+		break;
+	#ifdef _HAVE_BALANCED_
+	case BalancethicknessAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,ThicknessEnum);
+		break;
+	#endif
+	#ifdef _HAVE_HYDROLOGY_
+	case HydrologyDCInefficientAnalysisEnum:
+		InputUpdateFromSolutionHydrologyDCInefficient(solution);
+		break;
+	case HydrologyDCEfficientAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,EplHeadEnum);
+		break;
+	#endif
+	default: 
+		_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionPrognostic{{{*/
+void  Penta::InputUpdateFromSolutionPrognostic(IssmDouble* solution){
+
+	const int  numdof   = NDOF1*NUMVERTICES;
+	const int  numdof2d = NDOF1*NUMVERTICES2D;
+
+	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];
+	Penta  *penta   = NULL;
+
+	/*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 */
+	this->parameters->FindParam(&minthickness,PrognosticMinThicknessEnum);
+	for(i=0;i<numdof2d;i++){
+		newthickness[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(newthickness[i])) _error_("NaN found in solution vector");
+		/*Constrain thickness to be at least 1m*/
+		if(newthickness[i]<minthickness) newthickness[i]=minthickness;
+		newthickness[i+numdof2d]=newthickness[i];
+	}
+
+	/*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);
+
+	/*recover material parameters: */
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	for(i=0;i<numdof;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
+		}
+		else{ //so it is an ice shelf
+			if(hydroadjustment==AbsoluteEnum){
+				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
+			}
+			else _error_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
+		}
+	}
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	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));
+
+		/*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::InputUpdateFromSolutionOneDof{{{*/
+void  Penta::InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type){
+
+	const int numdof = NDOF1*NUMVERTICES;
+
+	IssmDouble values[numdof];
+	int*   doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new PentaP1Input(enum_type,values));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionOneDofCollpased{{{*/
+void  Penta::InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int enum_type){
+
+	const int  numdof   = NDOF1*NUMVERTICES;
+	const int  numdof2d = NDOF1*NUMVERTICES2D;
+
+	IssmDouble  values[numdof];
+	int*    doflist = NULL;
+	Penta  *penta   = NULL;
+
+	/*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(int i=0;i<numdof2d;i++){
+		values[i]         =solution[doflist[i]];
+		values[i+numdof2d]=values[i];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+		/*Add input to the element: */
+		penta->inputs->AddInput(new PentaP1Input(enum_type,values));
+
+		/*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::InputUpdateFromVector(IssmDouble* vector, int name, int type);{{{*/
+void  Penta::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;
+
+	switch(type){
+		case VertexPIdEnum: 
+			for (int i=0;i<NUMVERTICES;i++){
+				values[i]=vector[this->vertices[i]->Pid()];
+			}
+			/*update input*/
+			if (name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
+				material->inputs->AddInput(new PentaP1Input(name,values));
+			}
+			else{
+				this->inputs->AddInput(new PentaP1Input(name,values));
+			}
+			return;
+
+		case VertexSIdEnum: 
+			for (int i=0;i<NUMVERTICES;i++){
+				values[i]=vector[this->vertices[i]->Sid()];
+			}
+			/*update input*/
+			if (name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
+				material->inputs->AddInput(new PentaP1Input(name,values));
+			}
+			else{
+				this->inputs->AddInput(new PentaP1Input(name,values));
+			}
+			return;
+
+		case NodesEnum:
+			/*Get dof list: */
+			GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+			/*Use the dof list to index into the vector: */
+			for(int i=0;i<numdof;i++){
+				values[i]=vector[doflist[i]];
+				if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+			}
+			/*Add input to the element: */
+			this->inputs->AddInput(new PentaP1Input(name,values));
+
+			/*Free ressources:*/
+			xDelete<int>(doflist);
+			return;
+
+	  case NodeSIdEnum:
+			for(int i=0;i<NUMVERTICES;i++){
+				values[i]=vector[nodes[i]->Sid()];
+				if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+			}
+			/*Add input to the element: */
+			this->inputs->AddInput(new PentaP1Input(name,values));
+			
+			/*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!");
+}
+/*}}}*/
+/*FUNCTION Penta::IsOnBed{{{*/
+bool Penta::IsOnBed(void){
+
+	bool onbed;
+	inputs->GetInputValue(&onbed,MeshElementonbedEnum);
+	return onbed;
+}
+/*}}}*/
+/*FUNCTION Penta::IsInput{{{*/
+bool Penta::IsInput(int name){
+	if (
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==BedEnum ||
+				name==SurfaceSlopeXEnum ||
+				name==SurfaceSlopeYEnum ||
+				name==SurfaceforcingsMassBalanceEnum ||
+				name==BasalforcingsMeltingRateEnum ||
+				name==BasalforcingsGeothermalfluxEnum ||
+				name==SurfaceAreaEnum||
+				name==PressureEnum ||
+				name==VxEnum ||
+				name==VyEnum ||
+				name==VzEnum ||
+				name==VxMeshEnum ||
+				name==VyMeshEnum ||
+				name==VzMeshEnum ||
+				name==InversionVxObsEnum ||
+				name==InversionVyObsEnum ||
+				name==InversionVzObsEnum ||
+				name==TemperatureEnum ||
+				name==EnthalpyEnum ||
+				name==EnthalpyPicardEnum ||
+				name==WaterfractionEnum||
+				name==FrictionCoefficientEnum ||
+				name==GLlevelsetEnum ||
+				name==GradientEnum ||
+				name==OldGradientEnum  ||
+				name==ConvergedEnum || 
+				name==QmuVxEnum ||
+				name==QmuVyEnum ||
+				name==QmuVzEnum ||
+				name==QmuVxMeshEnum ||
+				name==QmuVyMeshEnum ||
+				name==QmuVzMeshEnum ||
+				name==QmuPressureEnum ||
+				name==QmuBedEnum ||
+				name==QmuThicknessEnum ||
+				name==QmuSurfaceEnum ||
+				name==QmuTemperatureEnum ||
+				name==QmuMeltingEnum ||
+				name==GiaWEnum || 
+				name==GiadWdtEnum ||
+				name==SedimentHeadEnum ||
+				name==EplHeadEnum ||
+				name==SedimentHeadOldEnum ||
+				name==EplHeadOldEnum ||
+				name==HydrologydcMaskEplactiveEnum ||
+				name==WaterTransferEnum
+				
+				) {
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
+/*FUNCTION Penta::IsFloating{{{*/
+bool   Penta::IsFloating(){
+
+	bool onshelf;
+	inputs->GetInputValue(&onshelf,MaskElementonfloatingiceEnum);
+	return onshelf;
+}
+/*}}}*/
+/*FUNCTION Penta::IsNodeOnShelf {{{*/
+bool   Penta::IsNodeOnShelf(){
+
+	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()])){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
+}
+/*}}}*/
+/*FUNCTION Penta::IsOnSurface{{{*/
+bool Penta::IsOnSurface(void){
+
+	bool onsurface;
+	inputs->GetInputValue(&onsurface,MeshElementonsurfaceEnum);
+	return onsurface;
+}
+/*}}}*/
+/*FUNCTION Penta::IsOnWater {{{*/
+bool   Penta::IsOnWater(){
+
+	bool onwater;
+	inputs->GetInputValue(&onwater,MaskElementonwaterEnum);
+	return onwater;
+}
+/*}}}*/
+/*FUNCTION Penta::ListResultsInfo{{{*/
+void Penta::ListResultsInfo(int** in_resultsenums,int** in_resultssizes,IssmDouble** in_resultstimes,int** in_resultssteps,int* in_num_results){
+
+	/*Intermediaries*/
+	int     i;
+	int     numberofresults = 0;
+	int     *resultsenums   = NULL;
+	int     *resultssizes   = NULL;
+	IssmDouble  *resultstimes   = NULL;
+	int     *resultssteps   = NULL;
+
+	/*Checks*/
+	_assert_(in_num_results);
+
+	/*Count number of results*/
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		numberofresults++;
+	}
+
+	if(numberofresults){
+
+		/*Allocate output*/
+		resultsenums=xNew<int>(numberofresults);
+		resultssizes=xNew<int>(numberofresults);
+		resultstimes=xNew<IssmDouble>(numberofresults);
+		resultssteps=xNew<int>(numberofresults);
+
+		/*populate enums*/
+		for(i=0;i<this->results->Size();i++){
+			ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+			resultsenums[i]=elementresult->InstanceEnum();
+			resultstimes[i]=elementresult->GetTime();
+			resultssteps[i]=elementresult->GetStep();
+			if(elementresult->ObjectEnum()==PentaP1ElementResultEnum){
+				resultssizes[i]=P1Enum;
+			}
+			else{
+				resultssizes[i]=P0Enum;
+			}
+		}
+	}
+
+	/*Assign output pointers:*/
+	*in_num_results=numberofresults;
+	*in_resultsenums=resultsenums;
+	*in_resultssizes=resultssizes;
+	*in_resultstimes=resultstimes;
+	*in_resultssteps=resultssteps;
+
+}/*}}}*/
+/*FUNCTION Penta::MinEdgeLength{{{*/
+IssmDouble Penta::MinEdgeLength(IssmDouble xyz_list[6][3]){
+	/*Return the minimum lenght of the nine egdes of the penta*/
+
+	int    i,node0,node1;
+	int    edges[9][2]={{0,1},{0,2},{1,2},{3,4},{3,5},{4,5},{0,3},{1,4},{2,5}}; //list of the nine edges
+	IssmDouble length;
+	IssmDouble minlength=-1;
+
+	for(i=0;i<9;i++){
+		/*Find the two nodes for this edge*/
+		node0=edges[i][0];
+		node1=edges[i][1];
+
+		/*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);
+		if(length<minlength || minlength<0) minlength=length;
+	}
+
+	return minlength;
+}
+/*}}}*/
+/*FUNCTION Penta::NodalValue {{{*/
+int    Penta::NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){
+
+	int i;
+	int found=0;
+	IssmDouble value;
+	Input* data=NULL;
+	GaussPenta* gauss=NULL;
+
+	/*First, serarch the input: */
+	data=inputs->GetInput(natureofdataenum); 
+
+	/*figure out if we have the vertex id: */
+	found=0;
+	for(i=0;i<NUMVERTICES;i++){
+		if(index==vertices[i]->Id()){
+			/*Do we have natureofdataenum in our inputs? :*/
+			if(data){
+				/*ok, we are good. retrieve value of input at vertex :*/
+				gauss=new GaussPenta(); gauss->GaussVertex(i);
+				data->GetInputValue(&value,gauss);
+				found=1;
+				break;
+			}
+		}
+	}
+
+	delete gauss;
+	if(found)*pvalue=value;
+	return found;
+}
+/*}}}*/
+/*FUNCTION Penta::PatchFill{{{*/
+void  Penta::PatchFill(int* pcount, Patch* patch){
+
+	int i,count;
+	int vertices_ids[6];
+
+	/*recover pointer: */
+	count=*pcount;
+
+	/*will be needed later: */
+	for(i=0;i<6;i++) vertices_ids[i]=vertices[i]->Id(); //vertices id start at column 3 of the patch.
+
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+
+		/*For this result,fill the information in the Patch object (element id + vertices ids), and then hand 
+		 *it to the result object, to fill the rest: */
+		patch->fillelementinfo(count,this->sid+1,vertices_ids,6);
+		elementresult->PatchFill(count,patch);
+
+		/*increment counter: */
+		count++;
+	}
+
+	/*Assign output pointers:*/
+	*pcount=count;
+}/*}}}*/
+/*FUNCTION Penta::PatchSize{{{*/
+void  Penta::PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes){
+
+	int     i;
+	int     numrows       = 0;
+	int     numnodes      = 0;
+	int     temp_numnodes = 0;
+
+	/*Go through all the results objects, and update the counters: */
+	for (i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		/*first, we have one more result: */
+		numrows++;
+		/*now, how many vertices and how many nodal values for this result? :*/
+		temp_numnodes=elementresult->NumberOfNodalValues(); //ask result object.
+		if(temp_numnodes>numnodes)numnodes=temp_numnodes;
+	}
+
+	/*Assign output pointers:*/
+	*pnumrows=numrows;
+	*pnumvertices=NUMVERTICES;
+	*pnumnodes=numnodes;
+}
+/*}}}*/
+/*FUNCTION Penta::PositiveDegreeDay{{{*/
+void  Penta::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){
+
+   IssmDouble agd[NUMVERTICES];             // surface mass balance
+   IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+   IssmDouble h[NUMVERTICES],s[NUMVERTICES]; // ,b
+   IssmDouble rho_water,rho_ice,desfac,s0p;
+
+   /*Recover monthly temperatures and precipitation*/
+   Input*     input=inputs->GetInput(SurfaceforcingsMonthlytemperaturesEnum); _assert_(input);
+   Input*     input2=inputs->GetInput(SurfaceforcingsPrecipitationEnum); _assert_(input2);
+   GaussPenta* gauss=new GaussPenta();
+   IssmDouble time,yts;
+   this->parameters->FindParam(&time,TimeEnum);
+   this->parameters->FindParam(&yts,ConstantsYtsEnum);
+   for(int month=0;month<12;month++) {
+     for(int iv=0;iv<NUMVERTICES;iv++) {
+       gauss->GaussVertex(iv);
+       input->GetInputValue(&monthlytemperatures[iv][month],gauss,time+month/12.*yts);
+       monthlytemperatures[iv][month]=monthlytemperatures[iv][month]-273.15; // conversion from Kelvin to celcius
+       input2->GetInputValue(&monthlyprec[iv][month],gauss,time+month/12.*yts);
+       monthlyprec[iv][month]=monthlyprec[iv][month]*yts; // convertion to m/yr
+     }
+   } 
+
+  /*Recover info at the vertices: */
+  GetInputListOnVertices(&h[0],ThicknessEnum);
+  GetInputListOnVertices(&s[0],SurfaceEnum);
+
+  /*Get material parameters :*/
+  rho_ice=matpar->GetRhoIce();
+  rho_water=matpar->GetRhoFreshwater();
+
+  /*Get desertification effect parameters*/
+  desfac=matpar->GetDesFac();
+  s0p=matpar->GetS0p();
+
+   /*measure the surface mass balance*/
+   for (int iv = 0; iv < NUMVERTICES; iv++){
+     agd[iv]=PddSurfaceMassBlance(&monthlytemperatures[iv][0], &monthlyprec[iv][0], pdds, pds, 
+				  signorm, yts, h[iv], s[iv], rho_ice, rho_water, desfac, s0p);
+     //printf("mass balance %f \n",agd[iv]);
+   }
+
+   /*Update inputs*/    
+   this->inputs->AddInput(new PentaP1Input(SurfaceforcingsMassBalanceEnum,&agd[0]));
+   //this->inputs->AddInput(new PentaVertexInput(ThermalSpcTemperatureEnum,&Tsurf[0]));
+   this->InputExtrude(SurfaceforcingsMassBalanceEnum,ElementEnum);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::ReduceMatrixStokes {{{*/
+void Penta::ReduceMatrixStokes(IssmDouble* Ke_reduced, IssmDouble* Ke_temp){
+
+	int    i,j;
+	IssmDouble Kii[24][24];
+	IssmDouble Kib[24][3];
+	IssmDouble Kbb[3][3];
+	IssmDouble Kbi[3][24];
+	IssmDouble Kbbinv[3][3];
+	IssmDouble Kright[24][24];
+
+	/*Create the four matrices used for reduction */
+	for(i=0;i<24;i++){
+		for(j=0;j<24;j++){
+			Kii[i][j]=*(Ke_temp+27*i+j);
+		}
+		for(j=0;j<3;j++){
+			Kib[i][j]=*(Ke_temp+27*i+j+24);
+		}
+	}
+	for(i=0;i<3;i++){
+		for(j=0;j<24;j++){
+			Kbi[i][j]=*(Ke_temp+27*(i+24)+j);
+		}
+		for(j=0;j<3;j++){
+			Kbb[i][j]=*(Ke_temp+27*(i+24)+j+24);
+		}
+	}
+
+	/*Inverse the matrix corresponding to bubble part Kbb */
+	Matrix3x3Invert(&Kbbinv[0][0], &Kbb[0][0]);
+
+	/*Multiply matrices to create the reduce matrix Ke_reduced */
+	TripleMultiply(&Kib[0][0],24,3,0,
+				&Kbbinv[0][0],3,3,0,
+				&Kbi[0][0],3,24,0,
+				&Kright[0][0],0);
+
+	/*Affect value to the reduced matrix */
+	for(i=0;i<24;i++) for(j=0;j<24;j++) *(Ke_reduced+24*i+j)=Kii[i][j]-Kright[i][j];
+}
+/*}}}*/
+/*FUNCTION Penta::ReduceVectorStokes {{{*/
+void Penta::ReduceVectorStokes(IssmDouble* Pe_reduced, IssmDouble* Ke_temp, IssmDouble* Pe_temp){
+
+	int    i,j;
+	IssmDouble Pi[24];
+	IssmDouble Pb[3];
+	IssmDouble Kbb[3][3];
+	IssmDouble Kib[24][3];
+	IssmDouble Kbbinv[3][3];
+	IssmDouble Pright[24];
+
+	/*Create the four matrices used for reduction */
+	for(i=0;i<24;i++) Pi[i]=*(Pe_temp+i);
+	for(i=0;i<3;i++) Pb[i]=*(Pe_temp+i+24);
+	for(j=0;j<3;j++){
+		for(i=0;i<24;i++){
+			Kib[i][j]=*(Ke_temp+3*i+j);
+		}
+		for(i=0;i<3;i++){
+			Kbb[i][j]=*(Ke_temp+3*(i+24)+j);
+		}
+	}
+
+	/*Inverse the matrix corresponding to bubble part Kbb */
+	Matrix3x3Invert(&Kbbinv[0][0], &Kbb[0][0]);
+
+	/*Multiply matrices to create the reduce matrix Ke_reduced */
+	TripleMultiply(&Kib[0][0],24,3,0,
+				&Kbbinv[0][0],3,3,0,
+				&Pb[0],3,1,0,&Pright[0],0);
+
+	/*Affect value to the reduced matrix */
+	for(i=0;i<24;i++) *(Pe_reduced+i)=Pi[i]-Pright[i];
+}
+/*}}}*/
+/*FUNCTION Penta::RequestedOutput{{{*/
+void Penta::RequestedOutput(int output_enum,int step,IssmDouble time){
+	if(IsInput(output_enum)){
+		/*just transfer this input to results, and we are done: */
+		InputToResult(output_enum,step,time);
+	}
+	else{
+		/*this input does not exist, compute it, and then transfer to results: */
+		switch(output_enum){
+			case BasalFrictionEnum:
+
+				/*create input: */
+				BasalFrictionCreateInput();
+
+				/*transfer to results :*/
+				InputToResult(output_enum,step,time);
+
+				/*erase input: */
+				inputs->DeleteInput(output_enum);
+				break;
+			case ViscousHeatingEnum:
+
+				/*create input: */
+				ViscousHeatingCreateInput();
+
+				/*transfer to results :*/
+				InputToResult(output_enum,step,time);
+
+				/*erase input: */
+				inputs->DeleteInput(output_enum);
+				break;
+
+			case StressTensorEnum: 
+				this->ComputeStressTensor();
+				InputToResult(StressTensorxxEnum,step,time);
+				InputToResult(StressTensorxyEnum,step,time);
+				InputToResult(StressTensorxzEnum,step,time);
+				InputToResult(StressTensoryyEnum,step,time);
+				InputToResult(StressTensoryzEnum,step,time);
+				InputToResult(StressTensorzzEnum,step,time);
+				break;
+
+			default:
+				/*do nothing, no need to derail the computation because one of the outputs requested cannot be found: */
+				break;
+		}
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::ResetCoordinateSystem{{{*/
+void  Penta::ResetCoordinateSystem(void){
+
+	int    approximation;
+	IssmDouble slopex[NUMVERTICES];
+	IssmDouble slopey[NUMVERTICES];
+	IssmDouble xz_plane[6];
+
+	/*For Stokes 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]);
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SetClone {{{*/
+void  Penta::SetClone(int* minranks){
+
+	_error_("not implemented yet");
+}
+/*}}}*/
+/*FUNCTION Penta::SetCurrentConfiguration {{{*/
+void  Penta::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){
+
+	int analysis_counter;
+
+	/*go into parameters and get the analysis_counter: */
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Pick up nodes */
+	if (this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::SetwiseNodeConnectivity{{{*/
+void Penta::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<6;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");
+			}
+		}
+	}
+
+	/*Special case: 2d/3d coupling, the node of this element might be connected
+	 *to the basal element*/
+	int analysis_type,approximation,numlayers;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	if(analysis_type==DiagnosticHorizAnalysisEnum){
+		inputs->GetInputValue(&approximation,ApproximationEnum);
+		if(approximation==MacAyealPattynApproximationEnum || approximation==MacAyealStokesApproximationEnum){
+			parameters->FindParam(&numlayers,MeshNumberoflayersEnum);
+			o_nz += numlayers*3;
+			d_nz += numlayers*3;
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
+}
+/*}}}*/
+/*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;
+
+	/*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();
+	tria->id=this->id;
+	tria->inputs=tria_inputs;
+	tria->results=tria_results;
+	tria->parameters=tria_parameters;
+	tria->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
+	this->SpawnTriaHook(dynamic_cast<ElementHook*>(tria),&indices[0]);
+
+	/*Spawn material*/
+	tria->material=NULL;
+	tria->material=(Material*)this->material->copy();
+	delete tria->material->inputs;
+	tria->material->inputs=(Inputs*)this->material->inputs->SpawnTriaInputs(indices);
+
+	/*recover nodes, material and matpar: */
+	tria->nodes=(Node**)tria->hnodes[analysis_counter]->deliverp();
+	tria->vertices=(Vertex**)tria->hvertices->deliverp();
+	tria->matpar=(Matpar*)tria->hmatpar->delivers();
+
+	return tria;
+}
+/*}}}*/
+/*FUNCTION Penta::SmbGradients{{{*/
+void Penta::SmbGradients(void){
+
+	int i;
+
+	// input
+   IssmDouble h[NUMVERTICES];					// ice thickness (m)		
+	IssmDouble s[NUMVERTICES];					// surface elevation (m)
+	IssmDouble b_pos[NUMVERTICES];				// Hs-SMB relation parameter
+	IssmDouble b_neg[NUMVERTICES];				// Hs-SMB relation paremeter
+	IssmDouble Href[NUMVERTICES];					// reference elevation from which deviations are used to calculate the SMB adjustment
+	IssmDouble Smbref[NUMVERTICES];				// reference SMB to which deviations are added
+   IssmDouble rho_water;                   // density of fresh water
+	IssmDouble rho_ice;                     // density of ice
+
+	// output
+	IssmDouble smb[NUMVERTICES];					// surface mass balance (m/yr ice)
+
+	/*Recover SmbGradients*/
+	GetInputListOnVertices(&Href[0],SurfaceforcingsHrefEnum);
+	GetInputListOnVertices(&Smbref[0],SurfaceforcingsSmbrefEnum);
+	GetInputListOnVertices(&b_pos[0],SurfaceforcingsBPosEnum);
+	GetInputListOnVertices(&b_neg[0],SurfaceforcingsBNegEnum);
+
+   /*Recover surface elevatio at vertices: */
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&s[0],SurfaceEnum);
+
+   /*Get material parameters :*/
+   rho_ice=matpar->GetRhoIce();
+   rho_water=matpar->GetRhoFreshwater();
+
+   // loop over all vertices
+ for(i=0;i<NUMVERTICES;i++){
+     if(Smbref[i]>0){
+		  smb[i]=Smbref[i]+b_pos[i]*(s[i]-Href[i]);
+	  }
+	  else{
+		  smb[i]=Smbref[i]+b_neg[i]*(s[i]-Href[i]);
+	  }
+	  smb[i]=smb[i]/rho_ice;      // SMB in m/y ice		
+	}  //end of the loop over the vertices
+	  /*Update inputs*/
+	  this->inputs->AddInput(new PentaP1Input(SurfaceforcingsMassBalanceEnum,&smb[0]));
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceArea {{{*/
+IssmDouble Penta::SurfaceArea(void){
+
+	int    approximation;
+	IssmDouble S;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())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())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*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).
+		S=tria->SurfaceArea();
+		delete tria->material; delete tria;
+		return S;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		S=tria->SurfaceArea();
+		delete tria->material; delete tria;
+		return S;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceNormal {{{*/
+void Penta::SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]){
+
+	int    i;
+	IssmDouble v13[3],v23[3];
+	IssmDouble normal[3];
+	IssmDouble normal_norm;
+
+	for (i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+
+	normal_norm=sqrt( pow(normal[0],2)+pow(normal[1],2)+pow(normal[2],2) );
+
+	*(surface_normal)=normal[0]/normal_norm;
+	*(surface_normal+1)=normal[1]/normal_norm;
+	*(surface_normal+2)=normal[2]/normal_norm;
+}
+/*}}}*/
+/*FUNCTION Penta::TimeAdapt{{{*/
+IssmDouble  Penta::TimeAdapt(void){
+
+	int    i;
+	IssmDouble C,dx,dy,dz,dt;
+	IssmDouble maxabsvx,maxabsvy,maxabsvz;
+	IssmDouble maxx,minx,maxy,miny,maxz,minz;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*get CFL coefficient:*/
+	this->parameters->FindParam(&C,TimesteppingCflCoefficientEnum);
+
+	/*Get for Vx and Vy, the max of abs value: */
+	this->MaxAbsVx(&maxabsvx);
+	this->MaxAbsVy(&maxabsvy);
+	this->MaxAbsVz(&maxabsvz);
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	minx=xyz_list[0][0];
+	maxx=xyz_list[0][0];
+	miny=xyz_list[0][1];
+	maxy=xyz_list[0][1];
+	minz=xyz_list[0][2];
+	maxz=xyz_list[0][2];
+
+	for(i=1;i<NUMVERTICES;i++){
+		if (xyz_list[i][0]<minx)minx=xyz_list[i][0];
+		if (xyz_list[i][0]>maxx)maxx=xyz_list[i][0];
+		if (xyz_list[i][1]<miny)miny=xyz_list[i][1];
+		if (xyz_list[i][1]>maxy)maxy=xyz_list[i][1];
+		if (xyz_list[i][2]<minz)minz=xyz_list[i][2];
+		if (xyz_list[i][2]>maxz)maxz=xyz_list[i][2];
+	}
+	dx=maxx-minx;
+	dy=maxy-miny;
+	dz=maxz-minz;
+
+	/*CFL criterion: */
+	dt=C/(maxabsvy/dx+maxabsvy/dy+maxabsvz/dz);
+
+	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){ 
+
+	/*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;
+	IssmDouble beta,heatcapacity,referencetemperature,meltingpoint,latentheat;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&beta,MaterialsBetaEnum);
+	iomodel->Constant(&heatcapacity,MaterialsHeatcapacityEnum);
+	iomodel->Constant(&referencetemperature,ConstantsReferencetemperatureEnum);
+	iomodel->Constant(&meltingpoint,MaterialsMeltingpointEnum);
+	iomodel->Constant(&latentheat,MaterialsLatentheatEnum);
+
+	/*Checks if debuging*/
+	/*{{{*/
+	_assert_(iomodel->Data(MeshElementsEnum));
+	/*}}}*/
+
+	/*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);
+
+	/*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
+
+	/*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
+	}
+
+	/*hooks: */
+	this->SetHookNodes(penta_node_ids,6,analysis_counter); this->nodes=NULL; //set hook to nodes, for this analysis type
+
+	/*Fill with IoModel*/
+	this->InputUpdateFromIoModel(index,iomodel);
+
+	/*Defaults if not provided in iomodel*/
+	switch(analysis_type){
+
+		case DiagnosticHorizAnalysisEnum:
+
+			/*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));
+			}
+			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));
+			}
+			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));
+			}
+			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));
+				}
+				if(isstokes){
+					this->inputs->AddInput(new PentaP1Input(PressureEnum,nodeinputs));
+					this->inputs->AddInput(new PentaP1Input(PressurePicardEnum,nodeinputs));
+				}
+			}
+			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));
+				}
+				else{
+					for(i=0;i<6;i++)nodeinputs[i]=0;
+					this->inputs->AddInput(new PentaP1Input(VzStokesEnum,nodeinputs));
+					this->inputs->AddInput(new PentaP1Input(VzPattynEnum,nodeinputs));
+				}
+			}
+			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));
+				}
+				else{
+					for(i=0;i<6;i++)nodeinputs[i]=0;
+					this->inputs->AddInput(new PentaP1Input(VzStokesEnum,nodeinputs));
+					this->inputs->AddInput(new PentaP1Input(VzMacAyealEnum,nodeinputs));
+				}
+			}
+			break;
+
+		case ThermalAnalysisEnum:
+			/*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));
+			if(dakota_analysis){
+				this->inputs->AddInput(new PentaP1Input(QmuVxMeshEnum,nodeinputs));
+				this->inputs->AddInput(new PentaP1Input(QmuVyMeshEnum,nodeinputs));
+				this->inputs->AddInput(new PentaP1Input(QmuVzMeshEnum,nodeinputs));
+			}
+			break;
+
+		case EnthalpyAnalysisEnum:
+			/*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));
+			if (iomodel->Data(TemperatureEnum) && iomodel->Data(WaterfractionEnum) && iomodel->Data(PressureEnum)) {
+				for(i=0;i<6;i++){
+					if(iomodel->Data(TemperatureEnum)[penta_vertex_ids[i]-1] < meltingpoint-beta*iomodel->Data(PressureEnum)[penta_vertex_ids[i]-1]){
+						nodeinputs[i]=heatcapacity*(iomodel->Data(TemperatureEnum)[penta_vertex_ids[i]-1]-referencetemperature);
+					}
+					else nodeinputs[i]=heatcapacity*
+					 (meltingpoint-beta*iomodel->Data(PressureEnum)[penta_vertex_ids[i]-1]-referencetemperature)
+						+latentheat*iomodel->Data(WaterfractionEnum)[penta_vertex_ids[i]-1];
+				}
+				this->inputs->AddInput(new PentaP1Input(EnthalpyEnum,nodeinputs));
+			}
+			else _error_("temperature and waterfraction required for the enthalpy solution");
+			break;
+
+		default:
+			/*No update for other solution types*/
+			break;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::UpdateConstraints{{{*/
+void Penta::UpdateConstraints(void){
+
+	/*Do nothing for now*/
+
+}
+/*}}}*/
+/*FUNCTION Penta::ViscousHeatingCreateInput {{{*/
+void Penta::ViscousHeatingCreateInput(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries*/
+	IssmDouble phi;
+	IssmDouble viscosity;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble epsilon[6];
+	IssmDouble viscousheating[NUMVERTICES]={0,0,0,0,0,0};
+	IssmDouble thickness;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*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* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/*loop over vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+
+		viscousheating[iv]=phi*thickness;
+	}
+
+	/*Create PentaVertex input, which will hold the basal friction:*/
+	this->inputs->AddInput(new PentaP1Input(ViscousHeatingEnum,&viscousheating[0]));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+
+#ifdef _HAVE_RESPONSES_
+/*FUNCTION Penta::AverageOntoPartition {{{*/
+void  Penta::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){
+	_error_("Not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::IceVolume {{{*/
+IssmDouble Penta::IceVolume(void){
+
+	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
+	IssmDouble base,height;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(IsOnWater())return 0;
+
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Pentangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height*/
+	height = 1./3.*((xyz_list[3][2]-xyz_list[0][2])+(xyz_list[4][2]-xyz_list[1][2])+(xyz_list[5][2]-xyz_list[2][2]));
+
+	/*Return: */
+	return base*height;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVel{{{*/
+void  Penta::MinVel(IssmDouble* pminvel){
+
+	/*Get minimum:*/
+	IssmDouble minvel=this->inputs->Min(VelEnum);
+
+	/*Assign output pointers:*/
+	*pminvel=minvel;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVx{{{*/
+void  Penta::MinVx(IssmDouble* pminvx){
+
+	/*Get minimum:*/
+	IssmDouble minvx=this->inputs->Min(VxEnum);
+
+	/*Assign output pointers:*/
+	*pminvx=minvx;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVy{{{*/
+void  Penta::MinVy(IssmDouble* pminvy){
+
+	/*Get minimum:*/
+	IssmDouble minvy=this->inputs->Min(VyEnum);
+
+	/*Assign output pointers:*/
+	*pminvy=minvy;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVz{{{*/
+void  Penta::MinVz(IssmDouble* pminvz){
+
+	/*Get minimum:*/
+	IssmDouble minvz=this->inputs->Min(VzEnum);
+
+	/*Assign output pointers:*/
+	*pminvz=minvz;
+}
+/*}}}*/
+/*FUNCTION Penta::MassFlux {{{*/
+IssmDouble Penta::MassFlux( IssmDouble* segment){
+
+	IssmDouble mass_flux=0;
+
+	if(!IsOnBed()) return mass_flux;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Spawn Tria element from the base of the Penta: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	mass_flux=tria->MassFlux(segment);
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return mass_flux;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxAbsVx{{{*/
+void  Penta::MaxAbsVx(IssmDouble* pmaxabsvx){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvx=this->inputs->MaxAbs(VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvx=maxabsvx;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxAbsVy{{{*/
+void  Penta::MaxAbsVy(IssmDouble* pmaxabsvy){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvy=this->inputs->MaxAbs(VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvy=maxabsvy;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxAbsVz{{{*/
+void  Penta::MaxAbsVz(IssmDouble* pmaxabsvz){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvz=this->inputs->MaxAbs(VzEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvz=maxabsvz;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVel{{{*/
+void  Penta::MaxVel(IssmDouble* pmaxvel){
+
+	/*Get maximum:*/
+	IssmDouble maxvel=this->inputs->Max(VelEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvel=maxvel;
+
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVx{{{*/
+void  Penta::MaxVx(IssmDouble* pmaxvx){
+
+	/*Get maximum:*/
+	IssmDouble maxvx=this->inputs->Max(VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvx=maxvx;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVy{{{*/
+void  Penta::MaxVy(IssmDouble* pmaxvy){
+
+	/*Get maximum:*/
+	IssmDouble maxvy=this->inputs->Max(VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvy=maxvy;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVz{{{*/
+void  Penta::MaxVz(IssmDouble* pmaxvz){
+
+	/*Get maximum:*/
+	IssmDouble maxvz=this->inputs->Max(VzEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvz=maxvz;
+}
+/*}}}*/
+/*FUNCTION Penta::ElementResponse{{{*/
+void Penta::ElementResponse(IssmDouble* presponse,int response_enum){
+
+	switch(response_enum){
+		case MaterialsRheologyBbarEnum:
+			*presponse=this->material->GetBbar();
+			break;
+		case MaterialsRheologyZbarEnum:
+			*presponse=this->material->GetZbar();
+			break;
+		case VelEnum:
+			{
+
+				/*Get input:*/
+				IssmDouble vel;
+				Input* vel_input;
+
+				vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+				vel_input->GetInputAverage(&vel);
+
+				/*Assign output pointers:*/
+				*presponse=vel;
+			}
+			break;
+		default:  
+			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::TotalSmb {{{*/
+IssmDouble Penta::TotalSmb(void){
+
+	/*The smb[Gt yr-1] of one element is area[m2] * smb [ m ice yr^-1] * rho_ice [kg m-3] / 1e+10^12 */
+	IssmDouble base,smb,rho_ice;
+	IssmDouble Total_Smb=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+	if(IsOnWater() || !IsOnSurface()) return 0.;
+
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average SMB over the element*/
+	Input* smb_input = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(smb_input);
+
+	smb_input->GetInputAverage(&smb);
+	Total_Smb=rho_ice*base*smb;// smb on element in kg s-1
+
+	/*Return: */
+	return Total_Smb;
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_GIA_
+/*FUNCTION Penta::GiaDeflection {{{*/
+void Penta::GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y){
+	_error_("GIA deflection not implemented yet!");
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_THERMAL_
+/*FUNCTION Penta::CreateKMatrixEnthalpy {{{*/
+ElementMatrix* Penta::CreateKMatrixEnthalpy(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixEnthalpyVolume();
+	ElementMatrix* Ke2=CreateKMatrixEnthalpyShelf();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixEnthalpyVolume {{{*/
+ElementMatrix* Penta::CreateKMatrixEnthalpyVolume(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        i,j,found=0;
+	IssmDouble Jdet,u,v,w,um,vm,wm;
+	IssmDouble h,hx,hy,hz,vx,vy,vz,vel;
+	IssmDouble gravity,rho_ice,rho_water;
+	IssmDouble epsvel=2.220446049250313e-16;
+	IssmDouble heatcapacity,thermalconductivity,dt;
+	IssmDouble pressure,enthalpy;
+	IssmDouble latentheat,kappa;
+	IssmDouble tau_parameter,diameter;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble B_conduct[3][numdof];
+	IssmDouble B_advec[3][numdof];
+	IssmDouble Bprime_advec[3][numdof];
+	IssmDouble L[numdof];
+	IssmDouble dbasis[3][6];
+	IssmDouble D_scalar_conduct,D_scalar_advec;
+	IssmDouble D_scalar_trans,D_scalar_stab;
+	IssmDouble D[3][3];
+	IssmDouble K[3][3]={0.0};
+	Tria*      tria=NULL;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	heatcapacity=matpar->GetHeatCapacity();
+	latentheat=matpar->GetLatentHeat();
+	thermalconductivity=matpar->GetThermalConductivity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,ThermalStabilizationEnum);
+	Input* pressure_input=inputs->GetInput(PressureEnum);      _assert_(pressure_input);
+	Input* enthalpy_input=inputs->GetInput(EnthalpyPicardEnum);_assert_(enthalpy_input); //for this iteration of the step
+	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* vxm_input=inputs->GetInput(VxMeshEnum);             _assert_(vxm_input);
+	Input* vym_input=inputs->GetInput(VyMeshEnum);             _assert_(vym_input);
+	Input* vzm_input=inputs->GetInput(VzMeshEnum);             _assert_(vzm_input);
+	if (stabilization==2) diameter=MinEdgeLength(xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Conduction: */  
+		/*Need to change that depending on enthalpy value -> cold or temperate ice: */  
+		GetBConduct(&B_conduct[0][0],&xyz_list[0][0],gauss); 
+
+		enthalpy_input->GetInputValue(&enthalpy, gauss);
+		pressure_input->GetInputValue(&pressure, gauss);
+		kappa=matpar->GetEnthalpyDiffusionParameter(enthalpy,pressure);
+		D_scalar_conduct=gauss->weight*Jdet*kappa;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar_conduct=D_scalar_conduct*dt;
+
+		D[0][0]=D_scalar_conduct; D[0][1]=0; D[0][2]=0;
+		D[1][0]=0; D[1][1]=D_scalar_conduct; D[1][2]=0;
+		D[2][0]=0; D[2][1]=0; D[2][2]=D_scalar_conduct;
+
+		TripleMultiply(&B_conduct[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&B_conduct[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Advection: */
+		GetBAdvec(&B_advec[0][0],&xyz_list[0][0],gauss); 
+		GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+		vx_input->GetInputValue(&u, gauss); vxm_input->GetInputValue(&um,gauss); vx=u-um; 
+		vy_input->GetInputValue(&v, gauss); vym_input->GetInputValue(&vm,gauss); vy=v-vm; 
+		vz_input->GetInputValue(&w, gauss); vzm_input->GetInputValue(&wm,gauss); vz=w-wm;
+
+		D_scalar_advec=gauss->weight*Jdet;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar_advec=D_scalar_advec*dt;
+
+		D[0][0]=D_scalar_advec*vx;D[0][1]=0;                D[0][2]=0;
+		D[1][0]=0;                D[1][1]=D_scalar_advec*vy;D[1][2]=0;
+		D[2][0]=0;                D[2][1]=0;                D[2][2]=D_scalar_advec*vz;
+
+		TripleMultiply(&B_advec[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&Bprime_advec[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Transient: */
+		if(reCast<bool,IssmDouble>(dt)){
+			GetNodalFunctionsP1(&L[0], gauss);
+			D_scalar_trans=gauss->weight*Jdet;
+
+			TripleMultiply(&L[0],numdof,1,0,
+						&D_scalar_trans,1,1,0,
+						&L[0],1,numdof,0,
+						&Ke->values[0],1);
+		}
+
+		/*Artifficial diffusivity*/
+		if(stabilization==1){
+			/*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.));
+			K[0][0]=h/(2*vel)*vx*vx;  K[0][1]=h/(2*vel)*vx*vy; K[0][2]=h/(2*vel)*vx*vz;
+			K[1][0]=h/(2*vel)*vy*vx;  K[1][1]=h/(2*vel)*vy*vy; K[1][2]=h/(2*vel)*vy*vz;
+			K[2][0]=h/(2*vel)*vz*vx;  K[2][1]=h/(2*vel)*vz*vy; K[2][2]=h/(2*vel)*vz*vz;
+			D_scalar_stab=gauss->weight*Jdet;
+			if(reCast<bool,IssmDouble>(dt)) D_scalar_stab=D_scalar_stab*dt;
+			for(i=0;i<3;i++) for(j=0;j<3;j++) K[i][j] = D_scalar_stab*K[i][j];
+
+			GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+			TripleMultiply(&Bprime_advec[0][0],3,numdof,1,
+						&K[0][0],3,3,0,
+						&Bprime_advec[0][0],3,numdof,0,
+						&Ke->values[0],1);
+		}
+		else if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+			tau_parameter=GetStabilizationParameter(u-um,v-vm,w-wm,diameter,kappa);
+
+			for(i=0;i<numdof;i++){
+				for(j=0;j<numdof;j++){
+					Ke->values[i*numdof+j]+=tau_parameter*D_scalar_advec*
+					  ((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i])*((u-um)*dbasis[0][j]+(v-vm)*dbasis[1][j]+(w-wm)*dbasis[2][j]);
+				}
+			}
+			if(reCast<bool,IssmDouble>(dt)){
+				for(i=0;i<numdof;i++){
+					for(j=0;j<numdof;j++){
+						Ke->values[i*numdof+j]+=tau_parameter*D_scalar_trans*L[j]*((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i]);
+					}
+				}
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixEnthalpyShelf {{{*/
+ElementMatrix* Penta::CreateKMatrixEnthalpyShelf(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j;
+	IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
+	IssmDouble rho_ice,rho_water,heatcapacity;
+	IssmDouble Jdet2d,dt;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble basis[NUMVERTICES];
+	IssmDouble D_scalar;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if (!IsOnBed() || !IsFloating()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	mixed_layer_capacity=matpar->GetMixedLayerCapacity();
+	thermal_exchange_velocity=matpar->GetThermalExchangeVelocity();
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	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];
+
+	/* Start looping on the number of gauss (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		D_scalar=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity/(rho_ice*heatcapacity);
+		if(reCast<bool,IssmDouble>(dt)) D_scalar=dt*D_scalar;
+
+		TripleMultiply(&basis[0],numdof,1,0,
+					&D_scalar,1,1,0,
+					&basis[0],1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixMelting {{{*/
+ElementMatrix* Penta::CreateKMatrixMelting(void){
+
+	if (!IsOnBed()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixMelting();
+
+	delete tria->material; delete tria;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixThermal {{{*/
+ElementMatrix* Penta::CreateKMatrixThermal(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixThermalVolume();
+	ElementMatrix* Ke2=CreateKMatrixThermalShelf();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixThermalVolume {{{*/
+ElementMatrix* Penta::CreateKMatrixThermalVolume(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        i,j,found=0;
+	IssmDouble Jdet,u,v,w,um,vm,wm,vel;
+	IssmDouble h,hx,hy,hz,vx,vy,vz;
+	IssmDouble gravity,rho_ice,rho_water,kappa;
+	IssmDouble heatcapacity,thermalconductivity,dt;
+	IssmDouble tau_parameter,diameter;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble B_conduct[3][numdof];
+	IssmDouble B_advec[3][numdof];
+	IssmDouble Bprime_advec[3][numdof];
+	IssmDouble L[numdof];
+	IssmDouble dbasis[3][6];
+	IssmDouble D_scalar_conduct,D_scalar_advec;
+	IssmDouble D_scalar_trans,D_scalar_stab;
+	IssmDouble D[3][3];
+	IssmDouble K[3][3]={0.0};
+	Tria*      tria=NULL;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	heatcapacity=matpar->GetHeatCapacity();
+	thermalconductivity=matpar->GetThermalConductivity();
+	kappa=thermalconductivity/(rho_ice*heatcapacity);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,ThermalStabilizationEnum);
+	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* vxm_input=inputs->GetInput(VxMeshEnum); _assert_(vxm_input);
+	Input* vym_input=inputs->GetInput(VyMeshEnum); _assert_(vym_input);
+	Input* vzm_input=inputs->GetInput(VzMeshEnum); _assert_(vzm_input);
+	if (stabilization==2) diameter=MinEdgeLength(xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Conduction: */
+
+		GetBConduct(&B_conduct[0][0],&xyz_list[0][0],gauss); 
+
+		D_scalar_conduct=gauss->weight*Jdet*kappa;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar_conduct=D_scalar_conduct*dt;
+
+		D[0][0]=D_scalar_conduct; D[0][1]=0; D[0][2]=0;
+		D[1][0]=0; D[1][1]=D_scalar_conduct; D[1][2]=0;
+		D[2][0]=0; D[2][1]=0; D[2][2]=D_scalar_conduct;
+
+		TripleMultiply(&B_conduct[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&B_conduct[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Advection: */
+
+		GetBAdvec(&B_advec[0][0],&xyz_list[0][0],gauss); 
+		GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+		vx_input->GetInputValue(&u, gauss); vxm_input->GetInputValue(&um,gauss); vx=u-um;
+		vy_input->GetInputValue(&v, gauss); vym_input->GetInputValue(&vm,gauss); vy=v-vm;
+		vz_input->GetInputValue(&w, gauss); vzm_input->GetInputValue(&wm,gauss); vz=w-wm;
+
+		D_scalar_advec=gauss->weight*Jdet;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar_advec=D_scalar_advec*dt;
+
+		D[0][0]=D_scalar_advec*vx;    D[0][1]=0;                    D[0][2]=0;
+		D[1][0]=0;                    D[1][1]=D_scalar_advec*vy;    D[1][2]=0;
+		D[2][0]=0;                    D[2][1]=0;                    D[2][2]=D_scalar_advec*vz;
+
+		TripleMultiply(&B_advec[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&Bprime_advec[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Transient: */
+		if(reCast<bool,IssmDouble>(dt)){
+			GetNodalFunctionsP1(&L[0], gauss);
+			D_scalar_trans=gauss->weight*Jdet;
+
+			TripleMultiply(&L[0],numdof,1,0,
+						&D_scalar_trans,1,1,0,
+						&L[0],1,numdof,0,
+						&Ke->values[0],1);
+		}
+
+		/*Artifficial diffusivity*/
+		if(stabilization==1){
+			/*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.));
+
+			K[0][0]=h/(2*vel)*fabs(vx*vx);  K[0][1]=h/(2*vel)*fabs(vx*vy); K[0][2]=h/(2*vel)*fabs(vx*vz);
+			K[1][0]=h/(2*vel)*fabs(vy*vx);  K[1][1]=h/(2*vel)*fabs(vy*vy); K[1][2]=h/(2*vel)*fabs(vy*vz);
+			K[2][0]=h/(2*vel)*fabs(vz*vx);  K[2][1]=h/(2*vel)*fabs(vz*vy); K[2][2]=h/(2*vel)*fabs(vz*vz);
+
+			D_scalar_stab=gauss->weight*Jdet;
+			if(reCast<bool,IssmDouble>(dt)) D_scalar_stab=D_scalar_stab*dt;
+			for(i=0;i<3;i++) for(j=0;j<3;j++) K[i][j] = D_scalar_stab*K[i][j];
+
+			GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+			TripleMultiply(&Bprime_advec[0][0],3,numdof,1,
+						&K[0][0],3,3,0,
+						&Bprime_advec[0][0],3,numdof,0,
+						&Ke->values[0],1);
+		}
+		else if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+			tau_parameter=GetStabilizationParameter(u-um,v-vm,w-wm,diameter,kappa);
+
+			for(i=0;i<numdof;i++){
+				for(j=0;j<numdof;j++){
+					Ke->values[i*numdof+j]+=tau_parameter*D_scalar_advec*
+					  ((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i])*((u-um)*dbasis[0][j]+(v-vm)*dbasis[1][j]+(w-wm)*dbasis[2][j]);
+				}
+			}
+			if(reCast<bool,IssmDouble>(dt)){
+				for(i=0;i<numdof;i++){
+					for(j=0;j<numdof;j++){
+						Ke->values[i*numdof+j]+=tau_parameter*D_scalar_trans*L[j]*((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i]);
+					}
+				}
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixThermalShelf {{{*/
+ElementMatrix* Penta::CreateKMatrixThermalShelf(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int       i,j;
+	IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
+	IssmDouble rho_ice,rho_water,heatcapacity;
+	IssmDouble Jdet2d,dt;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble basis[NUMVERTICES];
+	IssmDouble D_scalar;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if (!IsOnBed() || !IsFloating()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	mixed_layer_capacity=matpar->GetMixedLayerCapacity();
+	thermal_exchange_velocity=matpar->GetThermalExchangeVelocity();
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	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];
+
+	/* Start looping on the number of gauss (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		D_scalar=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity/(heatcapacity*rho_ice);
+		if(reCast<bool,IssmDouble>(dt)) D_scalar=dt*D_scalar;
+
+		TripleMultiply(&basis[0],numdof,1,0,
+					&D_scalar,1,1,0,
+					&basis[0],1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpy {{{*/
+ElementVector* Penta::CreatePVectorEnthalpy(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorEnthalpyVolume();
+	ElementVector* pe2=CreatePVectorEnthalpySheet();
+	ElementVector* pe3=CreatePVectorEnthalpyShelf();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpyVolume {{{*/
+ElementVector* Penta::CreatePVectorEnthalpyVolume(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries*/
+	int    i,j,found=0;
+	int    friction_type,stabilization;
+	IssmDouble Jdet,phi,dt;
+	IssmDouble rho_ice,heatcapacity;
+	IssmDouble thermalconductivity,kappa;
+	IssmDouble viscosity,pressure;
+	IssmDouble enthalpy,enthalpypicard;
+	IssmDouble tau_parameter,diameter;
+	IssmDouble u,v,w;
+	IssmDouble scalar_def,scalar_transient;
+	IssmDouble temperature_list[NUMVERTICES];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble L[numdof];
+	IssmDouble dbasis[3][6];
+	IssmDouble epsilon[6];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	thermalconductivity=matpar->GetThermalConductivity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,ThermalStabilizationEnum);
+	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* pressure_input=inputs->GetInput(PressureEnum);                      _assert_(pressure_input);
+	Input* enthalpy_input=NULL; 
+	Input* enthalpypicard_input=NULL; 
+	if(reCast<bool,IssmDouble>(dt)){
+		enthalpy_input=inputs->GetInput(EnthalpyEnum); _assert_(enthalpy_input);
+	}
+	if (stabilization==2){
+		diameter=MinEdgeLength(xyz_list);
+		enthalpypicard_input=inputs->GetInput(EnthalpyPicardEnum); _assert_(enthalpypicard_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(&L[0], gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+
+		scalar_def=phi/rho_ice*Jdet*gauss->weight;
+		if(reCast<bool,IssmDouble>(dt)) scalar_def=scalar_def*dt;
+
+		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
+
+		/* Build transient now */
+		if(reCast<bool,IssmDouble>(dt)){
+			enthalpy_input->GetInputValue(&enthalpy, gauss);
+			scalar_transient=enthalpy*Jdet*gauss->weight;
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_transient*L[i];
+		}
+
+		if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+
+			vx_input->GetInputValue(&u, gauss);
+			vy_input->GetInputValue(&v, gauss);
+			vz_input->GetInputValue(&w, gauss);
+			pressure_input->GetInputValue(&pressure, gauss);
+			enthalpypicard_input->GetInputValue(&enthalpypicard, gauss);
+			kappa=matpar->GetEnthalpyDiffusionParameter(enthalpy,pressure);
+			tau_parameter=GetStabilizationParameter(u,v,w,diameter,kappa);
+
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			if(reCast<bool,IssmDouble>(dt)){
+				for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpyShelf {{{*/
+ElementVector* Penta::CreatePVectorEnthalpyShelf(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j;
+	IssmDouble Jdet2d;
+	IssmDouble heatcapacity,h_pmp;
+	IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
+	IssmDouble rho_ice,rho_water,pressure,dt,scalar_ocean;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble basis[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	/* Ice/ocean heat exchange flux on ice shelf base */
+	if (!IsOnBed() || !IsFloating()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	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];
+	mixed_layer_capacity=matpar->GetMixedLayerCapacity();
+	thermal_exchange_velocity=matpar->GetThermalExchangeVelocity();
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		pressure_input->GetInputValue(&pressure,gauss);
+		h_pmp=matpar->PureIceEnthalpy(pressure);
+
+		scalar_ocean=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity*(h_pmp)/(rho_ice*heatcapacity);
+		if(reCast<bool,IssmDouble>(dt)) scalar_ocean=dt*scalar_ocean;
+
+		for(i=0;i<numdof;i++) pe->values[i]+=scalar_ocean*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpySheet {{{*/
+ElementVector* Penta::CreatePVectorEnthalpySheet(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j;
+	int        analysis_type;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	IssmDouble Jdet2d,dt;
+	IssmDouble rho_ice,heatcapacity,geothermalflux_value;
+	IssmDouble basalfriction,alpha2,vx,vy;
+	IssmDouble scalar,enthalpy,enthalpyup;
+	IssmDouble pressure,pressureup;
+	IssmDouble basis[NUMVERTICES];
+	Friction*  friction=NULL;
+	GaussPenta* gauss=NULL;
+	GaussPenta* gaussup=NULL;
+
+	/* Geothermal flux on ice sheet base and basal friction */
+	if (!IsOnBed() || IsFloating()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*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];
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	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* enthalpy_input=inputs->GetInput(EnthalpyEnum);             _assert_(enthalpy_input);
+	Input* pressure_input=inputs->GetInput(PressureEnum);             _assert_(pressure_input);
+	Input* geothermalflux_input=inputs->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
+
+	/*Build frictoin element, needed later: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	gaussup=new GaussPenta(3,4,5,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gaussup->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		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];
+//		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	delete gaussup;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorMelting {{{*/
+ElementVector* Penta::CreatePVectorMelting(void){
+	return NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermal {{{*/
+ElementVector* Penta::CreatePVectorThermal(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorThermalVolume();
+	ElementVector* pe2=CreatePVectorThermalSheet();
+	ElementVector* pe3=CreatePVectorThermalShelf();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermalVolume {{{*/
+ElementVector* Penta::CreatePVectorThermalVolume(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries*/
+	int    i,j,found=0;
+	int    friction_type,stabilization;
+	IssmDouble Jdet,phi,dt;
+	IssmDouble rho_ice,heatcapacity;
+	IssmDouble thermalconductivity,kappa;
+	IssmDouble viscosity,temperature;
+	IssmDouble tau_parameter,diameter;
+	IssmDouble u,v,w;
+	IssmDouble scalar_def,scalar_transient;
+	IssmDouble temperature_list[NUMVERTICES];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble L[numdof];
+	IssmDouble dbasis[3][6];
+	IssmDouble epsilon[6];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	thermalconductivity=matpar->GetThermalConductivity();
+	kappa=thermalconductivity/(rho_ice*heatcapacity);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,ThermalStabilizationEnum);
+	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* temperature_input=NULL;
+	if (reCast<bool,IssmDouble>(dt)) temperature_input=inputs->GetInput(TemperatureEnum); _assert_(inputs);
+	if (stabilization==2) diameter=MinEdgeLength(xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(&L[0], gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+
+		scalar_def=phi/(rho_ice*heatcapacity)*Jdet*gauss->weight;
+		if(reCast<bool,IssmDouble>(dt)) scalar_def=scalar_def*dt;
+
+		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
+
+		/* Build transient now */
+		if(reCast<bool,IssmDouble>(dt)){
+			temperature_input->GetInputValue(&temperature, gauss);
+			scalar_transient=temperature*Jdet*gauss->weight;
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_transient*L[i];
+		}
+
+		if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+
+			vx_input->GetInputValue(&u, gauss);
+			vy_input->GetInputValue(&v, gauss);
+			vz_input->GetInputValue(&w, gauss);
+
+			tau_parameter=GetStabilizationParameter(u,v,w,diameter,kappa);
+
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			if(reCast<bool,IssmDouble>(dt)){
+				for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermalShelf {{{*/
+ElementVector* Penta::CreatePVectorThermalShelf(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j;
+	IssmDouble Jdet2d;
+	IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
+	IssmDouble rho_ice,rho_water,pressure,dt,scalar_ocean;
+	IssmDouble heatcapacity,t_pmp;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble basis[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	/* Ice/ocean heat exchange flux on ice shelf base */
+	if (!IsOnBed() || !IsFloating()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	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];
+	mixed_layer_capacity=matpar->GetMixedLayerCapacity();
+	thermal_exchange_velocity=matpar->GetThermalExchangeVelocity();
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		pressure_input->GetInputValue(&pressure,gauss);
+		t_pmp=matpar->TMeltingPoint(pressure);
+
+		scalar_ocean=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity*(t_pmp)/(heatcapacity*rho_ice);
+		if(reCast<bool,IssmDouble>(dt)) scalar_ocean=dt*scalar_ocean;
+
+		for(i=0;i<numdof;i++) pe->values[i]+=scalar_ocean*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermalSheet {{{*/
+ElementVector* Penta::CreatePVectorThermalSheet(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j;
+	int        analysis_type;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	IssmDouble Jdet2d,dt;
+	IssmDouble rho_ice,heatcapacity,geothermalflux_value;
+	IssmDouble basalfriction,alpha2,vx,vy;
+	IssmDouble basis[NUMVERTICES];
+	IssmDouble scalar;
+	Friction*  friction=NULL;
+	GaussPenta* gauss=NULL;
+
+	/* Geothermal flux on ice sheet base and basal friction */
+	if (!IsOnBed() || IsFloating()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*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];
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	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* geothermalflux_input=inputs->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
+
+	/*Build frictoin element, needed later: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+			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)/(heatcapacity*rho_ice);
+			if(reCast<bool,IssmDouble>(dt)) scalar=dt*scalar;
+
+			for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsThermal{{{*/
+void  Penta::GetSolutionFromInputsThermal(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int         i;
+	int        *doflist = NULL;
+	IssmDouble  values[numdof];
+	IssmDouble  temp;
+	GaussPenta *gauss = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* t_input=inputs->GetInput(TemperatureEnum); _assert_(t_input);
+
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover temperature*/
+		gauss->GaussVertex(i);
+		t_input->GetInputValue(&temp,gauss);
+		values[i]=temp;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsEnthalpy{{{*/
+void  Penta::GetSolutionFromInputsEnthalpy(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble       values[numdof];
+	IssmDouble       enthalpy;
+	GaussPenta   *gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* h_input=inputs->GetInput(EnthalpyEnum); _assert_(h_input);
+
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover temperature*/
+		gauss->GaussVertex(i);
+		h_input->GetInputValue(&enthalpy,gauss);
+		values[i]=enthalpy;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionThermal {{{*/
+void  Penta::InputUpdateFromSolutionThermal(IssmDouble* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	bool        converged;
+	int         i,rheology_law;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  values[numdof];
+	IssmDouble  B[numdof];
+	IssmDouble  B_average,s_average;
+	int        *doflist = NULL;
+	IssmDouble  pressure[numdof];
+
+	/*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]];
+		//GetInputListOnVertices(&pressure[0],PressureEnum);
+		//if(values[i]>matpar->TMeltingPoint(pressure[i])) values[i]=matpar->TMeltingPoint(pressure[i]);
+		//if(values[i]<matpar->TMeltingPoint(pressure[i])-50) values[i]=matpar->TMeltingPoint(pressure[i])-50;
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+		//if(values[i]<0)      _printf_("temperature < 0°K found in solution vector\n");
+		//if(values[i]>275)    _printf_("temperature > 275°K found in solution vector (Paterson's rheology associated is negative)\n");
+	}
+
+	/*Get all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+
+	this->inputs->GetInputValue(&converged,ConvergedEnum);
+	if(converged){
+		this->inputs->AddInput(new PentaP1Input(TemperatureEnum,values));
+
+		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
+		 * otherwise the rheology could be negative*/
+		this->parameters->FindParam(&rheology_law,MaterialsRheologyLawEnum);
+		switch(rheology_law){
+			case NoneEnum:
+				/*Do nothing: B is not temperature dependent*/
+				break;
+			case PatersonEnum:
+				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));
+				break;
+			case ArrheniusEnum:
+				surface_input->GetInputAverage(&s_average);
+				B_average=Arrhenius((values[0]+values[1]+values[2]+values[3]+values[4]+values[5])/6.0,
+							s_average-((xyz_list[0][2]+xyz_list[1][2]+xyz_list[2][2]+xyz_list[3][2]+xyz_list[4][2]+xyz_list[5][2])/6.0),
+							material->GetN());
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->material->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			default:
+				_error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
+
+		}
+	}
+	else{
+		this->inputs->AddInput(new PentaP1Input(TemperaturePicardEnum,values));
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionEnthalpy {{{*/
+void  Penta::InputUpdateFromSolutionEnthalpy(IssmDouble* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	bool   converged=false;
+	int    i,rheology_law;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble values[numdof];
+	IssmDouble pressure[NUMVERTICES];
+	IssmDouble temperatures[numdof];
+	IssmDouble waterfraction[numdof];
+	IssmDouble B[numdof];
+	IssmDouble B_average,s_average;
+	int*   doflist=NULL;
+
+	/*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]];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GetInputListOnVertices(&pressure[0],PressureEnum);
+	Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+
+	this->inputs->GetInputValue(&converged,ConvergedEnum);
+	if(converged){
+		/*Convert enthalpy into temperature and water fraction*/
+		for(i=0;i<numdof;i++){
+			matpar->EnthalpyToThermal(&temperatures[i],&waterfraction[i],values[i],pressure[i]);
+			if(waterfraction[i]<0) _error_("Negative water fraction found in solution vector");
+			//if(waterfraction[i]>1) _error_("Water fraction >1 found in solution vector");
+		}
+
+		this->inputs->AddInput(new PentaP1Input(EnthalpyEnum,values));
+		this->inputs->AddInput(new PentaP1Input(WaterfractionEnum,waterfraction));
+		this->inputs->AddInput(new PentaP1Input(TemperatureEnum,temperatures));
+
+		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
+		 * otherwise the rheology could be negative*/
+		this->parameters->FindParam(&rheology_law,MaterialsRheologyLawEnum);
+		switch(rheology_law){
+			case NoneEnum:
+				/*Do nothing: B is not temperature dependent*/
+				break;
+			case PatersonEnum:
+				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));
+				break;
+			case ArrheniusEnum:
+				surface_input->GetInputAverage(&s_average);
+				B_average=Arrhenius((temperatures[0]+temperatures[1]+temperatures[2]+temperatures[3]+temperatures[4]+temperatures[5])/6.0,
+							s_average-((xyz_list[0][2]+xyz_list[1][2]+xyz_list[2][2]+xyz_list[3][2]+xyz_list[4][2]+xyz_list[5][2])/6.0),
+							material->GetN());
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->material->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			default:
+				_error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
+
+		}
+	}
+	else{
+		this->inputs->AddInput(new PentaP1Input(EnthalpyPicardEnum,values));
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_CONTROL_
+/*FUNCTION Penta::ControlInputGetGradient{{{*/
+void Penta::ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){
+
+	int vertexpidlist[NUMVERTICES];
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		if(!IsOnBed()) return;
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(enum_type==MaterialsRheologyZbarEnum){
+		if(!IsOnBed()) return;
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
+	}
+
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&vertexpidlist[0],control_index);
+	((ControlInput*)input)->GetGradient(gradient,&vertexpidlist[0]);
+
+}/*}}}*/
+/*FUNCTION Penta::ControlInputScaleGradient{{{*/
+void Penta::ControlInputScaleGradient(int enum_type,IssmDouble scale){
+
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(enum_type==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	((ControlInput*)input)->ScaleGradient(scale);
+}/*}}}*/
+/*FUNCTION Penta::ControlInputSetGradient{{{*/
+void Penta::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){
+
+	int    vertexpidlist[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(enum_type==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&vertexpidlist[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
+	grad_input=new PentaP1Input(GradientEnum,grad_list);
+	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+/*FUNCTION Penta::CreateKMatrixAdjointHoriz{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreateKMatrixAdjointMacAyeal2d();
+		case PattynApproximationEnum:
+			return CreateKMatrixAdjointPattyn();
+		case StokesApproximationEnum:
+			return CreateKMatrixAdjointStokes();
+		case NoneApproximationEnum:
+			return NULL;
+		default:
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixAdjointMacAyeal2d{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointMacAyeal2d(void){
+
+	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
+	  bedrock, in which case we spawn a tria element using the 3 first nodes, and use it to build 
+	  the stiffness matrix. */
+	if (!IsOnBed()) return NULL;
+
+	/*Depth average some fields*/
+	switch(this->material->ObjectEnum()){
+		case MaticeEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			break;
+		case MatdamageiceEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			this->InputDepthAverageAtBase(MaterialsRheologyZEnum,MaterialsRheologyZbarEnum,MaterialsEnum);
+			break;
+		default:
+			_error_("material "<<EnumToStringx(this->material->ObjectEnum())<<" not supported");
+	}
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixAdjointMacAyeal();
+	delete tria->material; delete tria;
+
+	/*Delete averaged fields*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->material->inputs->DeleteInput(MaterialsRheologyZbarEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixAdjointPattyn{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointPattyn(void){
+
+	/*Intermediaries */
+	int        i,j;
+	bool       incomplete_adjoint;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet;
+	IssmDouble eps1dotdphii,eps1dotdphij;
+	IssmDouble eps2dotdphii,eps2dotdphij;
+	IssmDouble mu_prime;
+	IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble eps1[3],eps2[3];
+	IssmDouble phi[NUMVERTICES];
+	IssmDouble dphi[3][NUMVERTICES];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Jacobian with regular Pattyn (first part of the Gateau derivative)*/
+	parameters->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
+	ElementMatrix* Ke=CreateKMatrixDiagnosticPattyn();
+	if(incomplete_adjoint) return Ke;
+
+	/*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);
+
+	/* 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);
+		GetNodalFunctionsP1Derivatives(&dphi[0][0],&xyz_list[0][0],gauss);
+
+		this->GetStrainRate3dPattyn(&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];
+		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
+		eps1[2]=epsilon[3];                eps2[2]=epsilon[4];
+
+		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];
+
+				Ke->values[12*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[12*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[12*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[12*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixAdjointStokes{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointStokes(void){
+
+	/*Constants*/
+	const int    numdof=NDOF4*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j;
+	bool       incomplete_adjoint;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet;
+	IssmDouble eps1dotdphii,eps1dotdphij;
+	IssmDouble eps2dotdphii,eps2dotdphij;
+	IssmDouble eps3dotdphii,eps3dotdphij;
+	IssmDouble mu_prime;
+	IssmDouble epsilon[5]; /* epsilon=[exx,eyy,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)*/
+	parameters->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
+	ElementMatrix* Ke=CreateKMatrixDiagnosticStokes();
+	if(incomplete_adjoint) return Ke;
+
+	/*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);
+
+	/* 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);
+		GetNodalFunctionsP1Derivatives(&dphi[0][0],&xyz_list[0][0],gauss);
+
+		this->GetStrainRate3dPattyn(&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];
+		eps1[1]=epsilon[2];   eps2[1]=epsilon[1];   eps3[1]=epsilon[4];
+		eps1[2]=epsilon[3];   eps2[2]=epsilon[4];   eps3[2]= -epsilon[0] -epsilon[1];
+
+		for(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;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointHoriz{{{*/
+ElementVector* Penta::CreatePVectorAdjointHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreatePVectorAdjointMacAyeal();
+		case PattynApproximationEnum:
+			return CreatePVectorAdjointPattyn();
+		case NoneApproximationEnum:
+			return NULL;
+		case StokesApproximationEnum:
+			return CreatePVectorAdjointStokes();
+		default:
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointMacAyeal{{{*/
+ElementVector* Penta::CreatePVectorAdjointMacAyeal(){
+
+	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->CreatePVectorAdjointHoriz();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointPattyn{{{*/
+ElementVector* Penta::CreatePVectorAdjointPattyn(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->CreatePVectorAdjointHoriz();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	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*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::GradientIndexing{{{*/
+void Penta::GradientIndexing(int* indexing,int control_index){
+
+	/*Get some parameters*/
+	int num_controls;
+	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+
+	/*get gradient indices*/
+	for(int i=0;i<NUMVERTICES;i++){
+		indexing[i]=num_controls*this->vertices[i]->Pid() + control_index;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::Gradj {{{*/
+void  Penta::Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index){
+	/*dJ/dalpha = ∂L/∂alpha = ∂J/∂alpha + ∂/∂alpha(KU-F)*/
+
+	int              i,approximation;
+	Tria*            tria=NULL;
+
+	/*If on water, skip grad (=0): */
+	if(IsOnWater())return;
+
+	/*First deal with ∂/∂alpha(KU-F)*/
+	switch(control_type){
+
+		case FrictionCoefficientEnum:
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			switch(approximation){
+				case MacAyealApproximationEnum:
+					GradjDragMacAyeal(gradient,control_index);
+					break;
+				case PattynApproximationEnum:
+					GradjDragPattyn(gradient,control_index);
+					break;
+				case StokesApproximationEnum:
+					GradjDragStokes(gradient,control_index);
+					break;
+				case NoneApproximationEnum:
+					/*Gradient is 0*/
+					break;
+				default:
+					_error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+
+		case MaterialsRheologyBbarEnum:
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			switch(approximation){
+				case MacAyealApproximationEnum:
+					GradjBbarMacAyeal(gradient,control_index);
+					break;
+				case PattynApproximationEnum:
+					GradjBbarPattyn(gradient,control_index);
+					break;
+				case StokesApproximationEnum:
+					GradjBbarStokes(gradient,control_index);
+					break;
+				case NoneApproximationEnum:
+					/*Gradient is 0*/
+					break;
+				default:
+					_error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+
+		default:
+			_error_("control type " << EnumToStringx(control_type) << " not supported yet: ");
+	}
+
+	/*Now deal with ∂J/∂alpha*/
+	int        *responses = NULL;
+	int         num_responses,resp;
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+
+		case ThicknessAbsMisfitEnum:
+		case SurfaceAbsVelMisfitEnum:
+		case SurfaceRelVelMisfitEnum:
+		case SurfaceLogVelMisfitEnum:
+		case SurfaceLogVxVyMisfitEnum:
+		case SurfaceAverageVelMisfitEnum:
+			/*Nothing, J does not depends on the parameter being inverted for*/
+			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;
+			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;
+			break;
+		default:
+			_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+	xDelete<int>(responses);
+}
+/*}}}*/
+/*FUNCTION Penta::GradjDragMacAyeal {{{*/
+void  Penta::GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Gradient is 0 if on shelf or not on bed*/
+	if(IsFloating() || !IsOnBed()) return;
+
+	/*Spawn tria*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	tria->GradjDragMacAyeal(gradient,control_index);
+	delete tria->material; delete tria;
+
+} /*}}}*/
+/*FUNCTION Penta::GradjDragPattyn {{{*/
+void  Penta::GradjDragPattyn(Vector<IssmDouble>* gradient,int control_index){
+
+	int        i,j;
+	int        analysis_type;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble vx,vy,lambda,mu,alpha_complement,Jdet;
+	IssmDouble bed,thickness,Neff,drag;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	IssmDouble dk[NDOF3]; 
+	IssmDouble grade_g[NUMVERTICES]={0.0};
+	IssmDouble grade_g_gaussian[NUMVERTICES];
+	IssmDouble basis[6];
+	Friction*  friction=NULL;
+	GaussPenta *gauss=NULL;
+
+	/*Gradient is 0 if on shelf or not on bed*/
+	if(IsFloating() || !IsOnBed()) return;
+
+	/*Retrieve all inputs and parameters*/
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	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];
+	Input* adjointx_input=inputs->GetInput(AdjointxEnum);               _assert_(adjointx_input);
+	Input* adjointy_input=inputs->GetInput(AdjointyEnum);               _assert_(adjointy_input);
+	Input* vx_input=inputs->GetInput(VxEnum);                           _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                           _assert_(vy_input);
+	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
+
+	/*Build frictoin element, needed later: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet, &xyz_list_tria[0][0],gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		/*Build alpha_complement_list: */
+		friction->GetAlphaComplement(&alpha_complement, gauss,VxEnum,VyEnum,VzEnum);
+
+		dragcoefficient_input->GetInputValue(&drag, gauss);
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*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*/
+		}
+
+		/*Add gradje_g_gaussian vector to gradje_g: */
+		for(i=0;i<NUMVERTICES;i++){
+			_assert_(!xIsNan<IssmDouble>(grade_g[i]));
+			grade_g[i]+=grade_g_gaussian[i];
+		}
+	}
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+}
+/*}}}*/
+/*FUNCTION Penta::GradjDragStokes {{{*/
+void  Penta::GradjDragStokes(Vector<IssmDouble>* gradient,int control_index){
+
+	int        i,j;
+	int        analysis_type;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble bed,thickness,Neff;
+	IssmDouble lambda,mu,xi,Jdet,vx,vy,vz;
+	IssmDouble alpha_complement,drag;
+	IssmDouble surface_normal[3],bed_normal[3];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	IssmDouble dk[NDOF3]; 
+	IssmDouble basis[6];
+	IssmDouble grade_g[NUMVERTICES]={0.0};
+	IssmDouble grade_g_gaussian[NUMVERTICES];
+	Friction*  friction=NULL;
+	GaussPenta* gauss=NULL;
+
+	/*Gradient is 0 if on shelf or not on bed*/
+	if(IsFloating() || !IsOnBed()) return;
+
+	/*Retrieve all inputs and parameters*/
+	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];
+	GradientIndexing(&vertexpidlist[0],control_index);
+	Input* drag_input    =inputs->GetInput(FrictionCoefficientEnum); _assert_(drag_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);
+	Input* adjointx_input=inputs->GetInput(AdjointxEnum);            _assert_(adjointx_input);
+	Input* adjointy_input=inputs->GetInput(AdjointyEnum);            _assert_(adjointy_input);
+	Input* adjointz_input=inputs->GetInput(AdjointzEnum);            _assert_(adjointz_input);
+
+	/*Build frictoin element, needed later: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/*Recover alpha_complement and drag: */
+		friction->GetAlphaComplement(&alpha_complement, gauss,VxEnum,VyEnum,VzEnum);
+		drag_input->GetInputValue(&drag,gauss);
+
+		/*recover lambda mu and xi: */
+		adjointx_input->GetInputValue(&lambda,gauss);
+		adjointy_input->GetInputValue(&mu    ,gauss);
+		adjointz_input->GetInputValue(&xi    ,gauss);
+
+		/*recover vx vy and vz: */
+		vx_input->GetInputValue(&vx, gauss);
+		vy_input->GetInputValue(&vy, gauss);
+		vz_input->GetInputValue(&vz, gauss);
+
+		/*Get normal vector to the bed */
+		SurfaceNormal(&surface_normal[0],xyz_list_tria);
+
+		bed_normal[0]=-surface_normal[0]; //Function is for upper surface, so the normal to the bed is the opposite of the result
+		bed_normal[1]=-surface_normal[1];
+		bed_normal[2]=-surface_normal[2];
+
+		/* Get Jacobian determinant: */
+		GetTriaJacobianDeterminant(&Jdet,&xyz_list_tria[0][0],gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		/*Get k derivative: dk/dx */
+		drag_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for (i=0;i<NUMVERTICES;i++){
+			//standard gradient dJ/dki
+			grade_g_gaussian[i]=(
+						-lambda*(2*drag*alpha_complement*(vx - vz*bed_normal[0]*bed_normal[2]))
+						-mu    *(2*drag*alpha_complement*(vy - vz*bed_normal[1]*bed_normal[2]))
+						-xi    *(2*drag*alpha_complement*(-vx*bed_normal[0]*bed_normal[2]-vy*bed_normal[1]*bed_normal[2]))
+						)*Jdet*gauss->weight*basis[i]; 
+		}
+
+		/*Add gradje_g_gaussian vector to gradje_g: */
+		for( i=0; i<NUMVERTICES; i++)grade_g[i]+=grade_g_gaussian[i];
+	}
+
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
+
+	delete friction;
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::GradjBbarMacAyeal {{{*/
+void  Penta::GradjBbarMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+
+	/*This element should be collapsed into a tria element at its base*/
+	if (!IsOnBed()) return; 
+
+	/*Depth Average B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*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);
+	delete tria->material; delete tria;
+
+	/*delete Average B*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+
+} /*}}}*/
+/*FUNCTION Penta::GradjBbarPattyn {{{*/
+void  Penta::GradjBbarPattyn(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Gradient is computed on bed only (Bbar)*/
+	if (!IsOnBed()) return;
+
+	/*Depth Average B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*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
+	delete tria->material; delete tria;
+
+	/*delete Average B*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+} /*}}}*/
+/*FUNCTION Penta::GradjBbarStokes {{{*/
+void  Penta::GradjBbarStokes(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Gradient is computed on bed only (Bbar)*/
+	if (!IsOnBed()) return;
+
+	/*Depth Average B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*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
+	delete tria->material; delete tria;
+
+	/*delete Average B*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+} /*}}}*/
+/*FUNCTION Penta::InputControlUpdate{{{*/
+void  Penta::InputControlUpdate(IssmDouble scalar,bool save_parameter){
+
+	/*Intermediary*/
+	int    num_controls;
+	int*   control_type=NULL;
+	Input* input=NULL;
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			if (!IsOnBed()) goto cleanup_and_return;
+			input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum); _assert_(input);
+		}
+		else if(control_type[i]==MaterialsRheologyZbarEnum){
+			if (!IsOnBed()) goto cleanup_and_return;
+			input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum); _assert_(input);
+		}
+		else{
+			input=(Input*)this->inputs->GetInput(control_type[i]); _assert_(input);
+		}
+
+		if (input->ObjectEnum()!=ControlInputEnum) _error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
+
+		((ControlInput*)input)->UpdateValue(scalar);
+		((ControlInput*)input)->Constrain();
+		if (save_parameter) ((ControlInput*)input)->SaveValue();
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			this->InputExtrude(MaterialsRheologyBEnum,MaterialsEnum);
+		}
+		else if(control_type[i]==MaterialsRheologyZbarEnum){
+			this->InputExtrude(MaterialsRheologyZEnum,MaterialsEnum);
+		}
+	}
+
+	/*Clean up and return*/
+cleanup_and_return:
+	xDelete<int>(control_type);
+}
+/*}}}*/
+/*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;
+
+	/*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<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");
+	}
+
+	/*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));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionAdjointHoriz {{{*/
+void  Penta::InputUpdateFromSolutionAdjointHoriz(IssmDouble* solution){
+
+	const int numdof=NDOF2*NUMVERTICES;
+
+	int    i;
+	IssmDouble values[numdof];
+	IssmDouble lambdax[NUMVERTICES];
+	IssmDouble lambday[NUMVERTICES];
+	int*   doflist=NULL;
+
+	/*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<NUMVERTICES;i++){
+		lambdax[i]=values[i*NDOF2+0];
+		lambday[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(lambdax[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i]))       _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(AdjointxEnum,lambdax));
+	this->inputs->AddInput(new PentaP1Input(AdjointyEnum,lambday));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceAverageVelMisfit {{{*/
+IssmDouble Penta::SurfaceAverageVelMisfit(int weight_index){
+
+	int    approximation;
+	IssmDouble J;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())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())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*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).
+		J=tria->SurfaceAverageVelMisfit(weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceAverageVelMisfit(weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceAbsVelMisfit {{{*/
+IssmDouble Penta::SurfaceAbsVelMisfit(int weight_index){
+
+	int    approximation;
+	IssmDouble J;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())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())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*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).
+		J=tria->SurfaceAbsVelMisfit(weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceAbsVelMisfit(weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceLogVelMisfit {{{*/
+IssmDouble Penta::SurfaceLogVelMisfit(int weight_index){
+
+	int    approximation;
+	IssmDouble J;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())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())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*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).
+		J=tria->SurfaceLogVelMisfit(weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceLogVelMisfit(weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceLogVxVyMisfit {{{*/
+IssmDouble Penta::SurfaceLogVxVyMisfit(int weight_index){
+
+	IssmDouble J;
+	Tria* tria=NULL;
+
+	/*inputs: */
+	int  approximation;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())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())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*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).
+		J=tria->SurfaceLogVxVyMisfit(weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceLogVxVyMisfit(weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceRelVelMisfit {{{*/
+IssmDouble Penta::SurfaceRelVelMisfit(int weight_index){
+
+	int    approximation;
+	IssmDouble J;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())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())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*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).
+		J=tria->SurfaceRelVelMisfit(weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceRelVelMisfit(weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::ThicknessAbsGradient{{{*/
+IssmDouble Penta::ThicknessAbsGradient(int weight_index){
+
+	_error_("Not implemented yet");
+}
+/*}}}*/
+/*FUNCTION Penta::ThicknessAbsMisfit {{{*/
+IssmDouble Penta::ThicknessAbsMisfit(int weight_index){
+
+	int    approximation;
+	IssmDouble J;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+	_error_("Not implemented yet");
+
+	tria=(Tria*)SpawnTria(0,1,2);
+	J=tria->ThicknessAbsMisfit(weight_index);
+	delete tria->material; delete tria;
+	return J;
+}
+/*}}}*/
+/*FUNCTION Penta::DragCoefficientAbsGradient{{{*/
+IssmDouble Penta::DragCoefficientAbsGradient(int weight_index){
+
+	IssmDouble J;
+	Tria*  tria=NULL;
+
+	/*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
+	J=tria->DragCoefficientAbsGradient(weight_index);
+	delete tria->material; delete tria;
+	return J;
+}
+/*}}}*/
+/*FUNCTION Penta::RheologyBbarAbsGradient{{{*/
+IssmDouble Penta::RheologyBbarAbsGradient(int weight_index){
+
+	IssmDouble J;
+	Tria*  tria=NULL;
+
+	/*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
+	J=tria->RheologyBbarAbsGradient(weight_index);
+	delete tria->material; delete tria;
+	return J;
+}
+/*}}}*/
+/*FUNCTION Penta::GetVectorFromControlInputs{{{*/
+void  Penta::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){
+
+	int vertexpidlist[NUMVERTICES];
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get input (either in element or material)*/
+	Input* input=inputs->GetInput(control_enum);
+	if(!input) _error_("Input " << EnumToStringx(control_enum) << " not found in element");
+
+	/*Check that it is a ControlInput*/
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
+}
+/*}}}*/
+/*FUNCTION Penta::SetControlInputsFromVector{{{*/
+void  Penta::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){
+
+	IssmDouble  values[NUMVERTICES];
+	int     vertexpidlist[NUMVERTICES];
+	Input  *input     = NULL;
+	Input  *new_input = NULL;
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get values on vertices*/
+	for (int i=0;i<NUMVERTICES;i++){
+		values[i]=vector[vertexpidlist[i]];
+	}
+	new_input = new PentaP1Input(control_enum,values);
+
+	if(control_enum==MaterialsRheologyBbarEnum){
+		input=(Input*)material->inputs->GetInput(control_enum); _assert_(input);
+	}
+	else{
+		input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	}
+
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->SetInput(new_input);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DAKOTA_
+/*FUNCTION Penta::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);{{{*/
+void  Penta::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
+
+	int i,j;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*New PentaP1Input*/
+			IssmDouble values[6];
+
+			/*Get values on the 6 vertices*/
+			for (i=0;i<6;i++){
+				values[i]=vector[this->vertices[i]->Sid()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
+			}
+
+			/*Branch on the specified type of update: */
+			switch(name){
+				case ThicknessEnum:
+					/*Update thickness + surface: assume bed is constant. On ice shelves, takes hydrostatic equilibrium {{{*/
+					IssmDouble  thickness[6];
+					IssmDouble  thickness_init[6];
+					IssmDouble  hydrostatic_ratio[6];
+					IssmDouble  surface[6];
+					IssmDouble  bed[6];
+
+					/*retrieve inputs: */
+					GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
+					GetInputListOnVertices(&hydrostatic_ratio[0],GeometryHydrostaticRatioEnum);
+					GetInputListOnVertices(&bed[0],BedEnum);
+					GetInputListOnVertices(&surface[0],SurfaceEnum);
+
+					/*build new thickness: */
+//					for(j=0;j<6;j++)thickness[j]=values[j];
+
+					/*build new bed and surface: */
+					if (this->IsFloating()){
+						/*hydrostatic equilibrium: */
+						IssmDouble rho_ice,rho_water,di;
+						rho_ice=this->matpar->GetRhoIce();
+						rho_water=this->matpar->GetRhoWater();
+
+						di=rho_ice/rho_water;
+
+						/*build new thickness: */
+						for (j=0; j<6; j++) {
+						/*  for observed/interpolated/hydrostatic thickness, remove scaling from any hydrostatic thickness  */
+							if     (hydrostatic_ratio[j] >= 0.)
+								thickness[j]=values[j]-(values[j]/thickness_init[j]-1.)*hydrostatic_ratio[j]*surface[j]/(1.-di);
+						/*  for minimum thickness, don't scale  */
+							else
+								thickness[j]=thickness_init[j];
+
+						/*  check the computed thickness and update bed  */
+							if (thickness[j] < 0.)
+								thickness[j]=1./(1.-di);
+							bed[j]=surface[j]-thickness[j];
+						}
+
+//						for(j=0;j<6;j++){
+//							surface[j]=(1-di)*thickness[j];
+//							bed[j]=-di*thickness[j];
+//						}
+					}
+					else{
+						/*build new thickness: */
+						for (j=0; j<6; j++) {
+						/*  for observed thickness, use scaled value  */
+							if(hydrostatic_ratio[j] >= 0.)
+								thickness[j]=values[j];
+						/*  for minimum thickness, don't scale  */
+							else
+								thickness[j]=thickness_init[j];
+						}
+
+						/*update bed on grounded ice: */
+//						for(j=0;j<6;j++)surface[j]=bed[j]+thickness[j];
+						for(j=0;j<6;j++)bed[j]=surface[j]-thickness[j];
+					}
+
+					/*Add new inputs: */
+					this->inputs->AddInput(new PentaP1Input(ThicknessEnum,thickness));
+					this->inputs->AddInput(new PentaP1Input(BedEnum,bed));
+					this->inputs->AddInput(new PentaP1Input(SurfaceEnum,surface));
+
+					/*}}}*/
+					break;
+				default:
+					this->inputs->AddInput(new PentaP1Input(name,values));
+			}
+			break;
+
+		default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+/*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;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*Create transient input: */
+
+			parameters->FindParam(&yts,ConstantsYtsEnum);
+
+			for(t=0;t<ncols;t++){ //ncols is the number of times
+
+				/*create input values: */
+				for(i=0;i<6;i++){
+					row=this->vertices[i]->Sid();
+					values[i]=(IssmDouble)matrix[ncols*row+t];
+				}
+
+				/*time? :*/
+				time=(IssmDouble)matrix[(nrows-1)*ncols+t]*yts;
+
+				if(t==0) transientinput=new TransientInput(name);
+				transientinput->AddTimeInput(new PentaP1Input(name,values),time);
+				transientinput->Configure(parameters);
+			}
+			this->inputs->AddInput(transientinput);
+			break;
+
+		default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DIAGNOSTIC_
+/*FUNCTION Penta::CreateDVectorDiagnosticHoriz {{{*/
+ElementVector* Penta::CreateDVectorDiagnosticHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case StokesApproximationEnum:
+			return CreateDVectorDiagnosticStokes();
+		default:
+			return NULL; //no need for doftypes outside of stokes approximation
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateDVectorDiagnosticStokes{{{*/
+ElementVector* Penta::CreateDVectorDiagnosticStokes(void){
+
+	/*output: */
+	ElementVector* De=NULL;
+	/*intermediary: */
+	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;
+	}
+
+	return De;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattyn{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattyn(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixCouplingMacAyealPattynViscous();
+	ElementMatrix* Ke2=CreateKMatrixCouplingMacAyealPattynFriction();
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattynViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattynViscous(void){
+
+	/*Constants*/
+	const int numnodes    = 2 *NUMVERTICES;
+	const int numdofm     = NDOF2 *NUMVERTICES2D;
+	const int numdofp     = NDOF2 *NUMVERTICES;
+	const int numdoftotal = 2 *NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int         i,j;
+	IssmDouble  Jdet;
+	IssmDouble  viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
+	IssmDouble  epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  B[3][numdofp];
+	IssmDouble  Bprime[3][numdofm];
+	IssmDouble  D[3][3]={0.0};            // material matrix, simple scalar matrix.
+	IssmDouble  D_scalar;
+	IssmDouble  Ke_gg[numdofp][numdofm]={0.0}; //local element stiffness matrix 
+	IssmDouble  Ke_gg_gaussian[numdofp][numdofm]; //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 pattyn 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*/
+	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] = XYEnum;
+	}
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke1=new ElementMatrix(pentabase->nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(this->nodes     ,NUMVERTICES,this->parameters,PattynApproximationEnum);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vxold_input=inputs->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vyold_input=inputs->GetInput(VyPicardEnum); _assert_(vyold_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussTria(gauss_tria);
+
+		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);
+		material->GetViscosity3d(&viscosity, &epsilon[0]);
+		material->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
+
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],3,numdofp,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdofm,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		for( i=0; i<numdofp; i++) for(j=0;j<numdofm; j++) Ke_gg[i][j]+=Ke_gg_gaussian[i][j];
+	} 
+	for(i=0;i<numdofp;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<numdofp;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg[j][i];
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean-up and return*/
+	delete tria->material; delete tria;
+	delete gauss;
+	delete gauss_tria;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattynFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattynFriction(void){
+
+	/*Constants*/
+	const int numnodes    = 2 *NUMVERTICES;
+	const int numdof      = NDOF2 *NUMVERTICES;
+	const int numdoftotal = NDOF4 *NUMVERTICES;
+
+	/*Intermediaries */
+	int       i,j,analysis_type;
+	IssmDouble Jdet2d,alpha2;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	IssmDouble L[2][numdof];
+	IssmDouble DL[2][2]                  ={{ 0,0 },{0,0}}; //for basal drag
+	IssmDouble DL_scalar;
+	IssmDouble Ke_gg[numdof][numdof]     ={0.0};
+	IssmDouble Ke_gg_gaussian[numdof][numdof]; //stiffness matrix contribution from drag
+	Friction  *friction = NULL;
+	GaussPenta *gauss=NULL;
+	Node       *node_list[numnodes];
+	int         cs_list[numnodes];
+
+	/*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* 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] = XYEnum;
+	}
+
+	/*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];
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	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);
+
+	/*build friction object, used later on: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/* 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);
+
+		/*Friction: */
+		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		GetBPattynFriction(&L[0][0],gauss);
+
+		DL_scalar=alpha2*gauss->weight*Jdet2d;
+		for (i=0;i<2;i++) DL[i][i]=DL_scalar; 
+
+		/*  Do the triple producte tL*D*L: */
+		TripleMultiply( &L[0][0],2,numdof,1,
+					&DL[0][0],2,2,0,
+					&L[0][0],2,numdof,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke_gg[i][j]+=Ke_gg_gaussian[i][j];
+	}
+
+	for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdoftotal+(numdof+j)]+=Ke_gg[i][j];
+	for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[(i+numdof)*numdoftotal+j]+=Ke_gg[i][j];
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealStokes{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealStokes(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixCouplingMacAyealStokesViscous();
+	ElementMatrix* Ke2=CreateKMatrixCouplingMacAyealStokesFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealStokesViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealStokesViscous(void){
+
+	/*Constants*/
+	const int numnodes    = 2 *NUMVERTICES;
+	const int numdofm     = NDOF2 *NUMVERTICES2D;
+	const int numdofs     = NDOF4 *NUMVERTICES;
+	const int numdoftotal = 2 *numdofm+numdofs;
+
+	/*Intermediaries */
+	int         i,j;
+	IssmDouble Jdet;
+	IssmDouble viscosity,stokesreconditioning; //viscosity
+	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble B[4][numdofs+3];
+	IssmDouble Bprime[4][numdofm];
+	IssmDouble B2[3][numdofm];
+	IssmDouble Bprime2[3][numdofs+3];
+	IssmDouble D[4][4]={0.0};            // material matrix, simple scalar matrix.
+	IssmDouble D2[3][3]={0.0};            // material matrix, simple scalar matrix.
+	IssmDouble D_scalar;
+	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.
+	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: */
+	Penta* pentabase=GetBasalElement();
+	Tria* tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	/*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;
+	}
+
+	/*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);
+	delete Ke1; delete Ke2;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	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);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussTria(gauss_tria);
+
+		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);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		material->GetViscosity3dStokes(&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;
+		for (i=0;i<3;i++) D2[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],4,numdofs+3,1,
+					&D[0][0],4,4,0,
+					&Bprime[0][0],4,numdofm,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		TripleMultiply( &B2[0][0],3,numdofm,1,
+					&D2[0][0],3,3,0,
+					&Bprime2[0][0],3,numdofs+3,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->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*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean-up and return*/
+	delete tria->material; delete tria;
+	delete gauss;
+	delete gauss_tria;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealStokesFriction {{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealStokesFriction(void){
+
+	/*Constants*/
+	const int numnodes  = 2 *NUMVERTICES;
+	const int numdof    = NUMVERTICES *NDOF4;
+	const int numdofm   = NUMVERTICES *NDOF2;
+	const int numdof2d  = NUMVERTICES2D *NDOF4;
+	const int numdof2dm = NUMVERTICES2D *NDOF2;
+	const int numdoftot = numdof+numdofm;
+
+	/*Intermediaries */
+	int        i,j;
+	int        analysis_type,approximation;
+	IssmDouble stokesreconditioning;
+	IssmDouble viscosity,alpha2_gauss,Jdet2d;
+	IssmDouble bed_normal[3];
+	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	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 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: */
+	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);
+	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);
+	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);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*build friction object, used later on: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* 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(&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);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		material->GetViscosity3dStokes(&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,
+					&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,
+					&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<numdof2d;i++) for(j=0;j<numdof2dm;j++) Ke->values[(i+numdofm)*numdoftot+j]+=Ke_drag_gaussian2[i][j];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingPattynStokes{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingPattynStokes(void){
+
+	/*Constants*/
+	const int numnodes  = 2 *NUMVERTICES;
+	const int numdofp     = NDOF2 *NUMVERTICES;
+	const int numdofs     = NDOF4 *NUMVERTICES;
+	const int numdoftotal = (NDOF2+NDOF4) *NUMVERTICES;
+
+	/*Intermediaries*/
+	Node     *node_list[numnodes];
+	int       cs_list[numnodes];
+	int       i,j;
+
+	/*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;
+	}
+
+	/*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* 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);
+
+	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];
+	}
+	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*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticHoriz {{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreateKMatrixDiagnosticMacAyeal2d();
+		case L1L2ApproximationEnum:
+			return CreateKMatrixDiagnosticL1L2();
+		case PattynApproximationEnum:
+			return CreateKMatrixDiagnosticPattyn();
+		case StokesApproximationEnum:
+			return CreateKMatrixDiagnosticStokes();
+		case HutterApproximationEnum:
+			return NULL;
+		case NoneApproximationEnum:
+			return NULL;
+		case MacAyealPattynApproximationEnum:
+			return CreateKMatrixDiagnosticMacAyealPattyn();
+		case MacAyealStokesApproximationEnum:
+			return CreateKMatrixDiagnosticMacAyealStokes();
+		case PattynStokesApproximationEnum:
+			return CreateKMatrixDiagnosticPattynStokes();
+		default:
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticHutter{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticHutter(void){
+
+	/*Constants*/
+	const int numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int         connectivity[2];
+	int         i,i0,i1,j0,j1;
+	IssmDouble  one0,one1;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Spawn 3 beam elements: */
+	for(i=0;i<3;i++){
+		/*2 dofs of first node*/
+		i0=2*i;
+		i1=2*i+1;
+		/*2 dofs of second node*/
+		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];
+
+		/*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;
+		}
+		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;
+		}
+		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;
+		}
+		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;
+		}
+	}
+
+	/*Clean up and return*/
+	return Ke;
+}/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal2d{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal2d(void){
+
+	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
+	  bedrock, in which case we spawn a tria element using the 3 first nodes, and use it to build 
+	  the stiffness matrix. */
+	if (!IsOnBed()) return NULL;
+
+	/*Depth average some fields*/
+	switch(this->material->ObjectEnum()){
+		case MaticeEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			break;
+		case MatdamageiceEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			this->InputDepthAverageAtBase(MaterialsRheologyZEnum,MaterialsRheologyZbarEnum,MaterialsEnum);
+			break;
+		default:
+			_error_("material "<<EnumToStringx(this->material->ObjectEnum())<<" not supported");
+	}
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyeal();
+	delete tria->material; delete tria;
+
+	/*Delete averaged fields*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->material->inputs->DeleteInput(MaterialsRheologyZbarEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3d{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3d(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3dViscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticMacAyeal3dFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3dViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3dViscous(void){
+
+	/*Constants*/
+	const int    numdof2d=2*NUMVERTICES2D;
+
+	/*Intermediaries */
+	int         i,j,approximation;
+	IssmDouble  Jdet;
+	IssmDouble  viscosity , oldviscosity, newviscosity, viscosity_overshoot;
+	IssmDouble  epsilon[5],oldepsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble  epsilons[6];                    //6 for stokes
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  B[3][numdof2d];
+	IssmDouble  Bprime[3][numdof2d];
+	IssmDouble  D[3][3]= {0.0};                 // material matrix, simple scalar matrix.
+	IssmDouble  D_scalar;
+	IssmDouble  Ke_gg_gaussian[numdof2d][numdof2d];
+	Tria       *tria       = NULL;
+	Penta      *pentabase  = NULL;
+	GaussPenta *gauss      = NULL;
+	GaussTria  *gauss_tria = NULL;
+
+	/*Find penta on bed as this is a macayeal elements: */
+	pentabase=GetBasalElement();
+	tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(tria->nodes,NUMVERTICES2D,this->parameters,MacAyealApproximationEnum);
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vxold_input=inputs->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vyold_input=inputs->GetInput(VyPicardEnum); _assert_(vyold_input);
+	Input* vz_input=inputs->GetInput(VzEnum);       _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussTria(gauss_tria);
+
+		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);
+			material->GetViscosity3d(&viscosity, &epsilon[0]);
+			material->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
+
+			newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		}
+		else if (approximation==MacAyealStokesApproximationEnum){
+			this->GetStrainRate3d(&epsilons[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+			material->GetViscosity3dStokes(&newviscosity,&epsilons[0]);
+		}
+		else _error_("approximation " << approximation << " (" << EnumToStringx(approximation) << ") not supported yet");
+
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],3,numdof2d,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdof2d,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof2d+j]+=Ke_gg_gaussian[i][j];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,tria->nodes,NUMVERTICES2D,XYEnum);
+
+	/*Clean up and return*/
+	delete tria->material;
+	delete tria;
+	delete gauss_tria;
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3dFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3dFriction(void){
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !IsOnBed()) return NULL;
+
+	/*Build a tria element using the 3 nodes of the base of the penta. Then use 
+	 * the tria functionality to build a friction stiffness matrix on these 3
+	 * nodes: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyealFriction();
+	delete tria->material; delete tria;
+
+	/*clean-up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyealPattyn{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyealPattyn(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3d();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticPattyn();
+	ElementMatrix* Ke3=CreateKMatrixCouplingMacAyealPattyn();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyealStokes{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyealStokes(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3d();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticStokes();
+	ElementMatrix* Ke3=CreateKMatrixCouplingMacAyealStokes();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticL1L2Viscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticL1L2Friction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2Viscous{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2Viscous(void){
+
+	/*Constants*/
+	const int    numdof2d=2*NUMVERTICES2D;
+
+	/*Intermediaries */
+	int         i,j;
+	IssmDouble  Jdet,viscosity;
+	IssmDouble  epsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  B[3][numdof2d];
+	IssmDouble  Bprime[3][numdof2d];
+	IssmDouble  Ke_gg_gaussian[numdof2d][numdof2d];
+	IssmDouble  D[3][3]= {0.0};                 // material matrix, simple scalar matrix.
+	Tria       *tria       = NULL;
+	Penta      *pentabase  = NULL;
+	GaussPenta *gauss      = NULL;
+	GaussTria  *gauss_tria = NULL;
+
+	/*Find penta on bed as this is a macayeal elements: */
+	pentabase=GetBasalElement();
+	tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(tria->nodes,NUMVERTICES2D,this->parameters,L1L2ApproximationEnum);
+
+	/*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* surf_input=inputs->GetInput(SurfaceEnum); _assert_(surf_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussTria(gauss_tria);
+
+		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);
+
+		/*Get viscosity for L1L2 model*/
+		GetL1L2Viscosity(&viscosity,&xyz_list[0][0],gauss,vx_input,vy_input,surf_input);
+
+		for(i=0;i<3;i++) D[i][i]=2*viscosity*gauss->weight*Jdet;
+
+		TripleMultiply( &B[0][0],3,numdof2d,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdof2d,0,
+					&Ke_gg_gaussian[0][0],0);
+		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof2d+j]+=Ke_gg_gaussian[i][j];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,tria->nodes,NUMVERTICES2D,XYEnum);
+
+	/*Clean up and return*/
+	delete tria->material;
+	delete tria;
+	delete gauss_tria;
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2Friction{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2Friction(void){
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !IsOnBed()) return NULL;
+
+	/*Build a tria element using the 3 nodes of the base of the penta. Then use 
+	 * the tria functionality to build a friction stiffness matrix on these 3
+	 * nodes: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyealFriction();
+	delete tria->material; delete tria;
+
+	/*clean-up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattyn{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattyn(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticPattynViscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticPattynFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattynViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattynViscous(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*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;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vxold_input=inputs->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vyold_input=inputs->GetInput(VyPicardEnum); _assert_(vyold_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);
+		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);
+		material->GetViscosity3d(&viscosity, &epsilon[0]);
+		material->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+
+		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,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattynFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattynFriction(void){
+
+	/*Constants*/
+	const int numdof   = NDOF2*NUMVERTICES;
+
+	/*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;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !IsOnBed()) return NULL;
+
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+
+	/*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];
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_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);
+
+	/*build friction object, used later on: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/*Recover portion of element that is grounded*/
+	if(migration_style==SubelementMigrationEnum) phi=this->GetGroundedPortion(&xyz_list[0][0]);
+
+	/* 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);
+
+		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum); 
+		if(migration_style==SubelementMigrationEnum) alpha2=phi*alpha2;
+
+		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,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattynStokes{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattynStokes(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticPattyn();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticStokes();
+	ElementMatrix* Ke3=CreateKMatrixCouplingPattynStokes();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticStokes{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticStokes(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticStokesViscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticStokesFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticStokesViscous {{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticStokesViscous(void){
+
+	/*Intermediaries */
+	int        i,approximation;
+	IssmDouble Jdet,viscosity,stokesreconditioning;
+	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 D[8][8]={0.0};
+	IssmDouble Ke_temp[27][27]={0.0}; //for the six nodes and the bubble 
+	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);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	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);
+
+	/* 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);
+		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]);
+
+		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]);
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticStokesFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticStokesFriction(void){
+
+	/*Constants*/
+	const int numdof=NUMVERTICES*NDOF4;
+	const int numdof2d=NUMVERTICES2D*NDOF4;
+
+	/*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: */
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(IsFloating() || !IsOnBed() || (approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum &&  approximation!=PattynStokesApproximationEnum)) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	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);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*build friction object, used later on: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* 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(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		GetLStokes(&LStokes[0][0], 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];
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+	//TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticVert {{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticVert(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticVertVolume();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticVertSurface();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticVertVolume {{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticVertVolume(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	IssmDouble  Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  B[NDOF1][NUMVERTICES];
+	IssmDouble  Bprime[NDOF1][NUMVERTICES];
+	IssmDouble  DL_scalar;
+	GaussPenta  *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBVert(&B[0][0], &xyz_list[0][0], gauss);
+		GetBprimeVert(&Bprime[0][0], &xyz_list[0][0], gauss);
+
+		DL_scalar=gauss->weight*Jdet;
+
+		TripleMultiply( &B[0][0],1,NUMVERTICES,1,
+					&DL_scalar,1,1,0,
+					&Bprime[0][0],1,NUMVERTICES,0,
+					&Ke->values[0],1);
+	} 
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticVertSurface {{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticVertSurface(void){
+
+	if (!IsOnSurface()) return NULL;
+
+	/*Constants*/
+	const int numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int       i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble surface_normal[3];
+	IssmDouble Jdet2d,DL_scalar;
+	IssmDouble basis[NUMVERTICES];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	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+3][j];
+	SurfaceNormal(&surface_normal[0],xyz_list_tria);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(3,4,5,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		DL_scalar= - gauss->weight*Jdet2d*surface_normal[2]; 
+
+		TripleMultiply( basis,1,numdof,1,
+					&DL_scalar,1,1,0,
+					basis,1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingMacAyealStokes {{{*/
+ElementVector* Penta::CreatePVectorCouplingMacAyealStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorCouplingMacAyealStokesViscous();
+	ElementVector* pe2=CreatePVectorCouplingMacAyealStokesFriction();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingMacAyealStokesViscous {{{*/
+ElementVector* Penta::CreatePVectorCouplingMacAyealStokesViscous(void){
+
+	/*Constants*/
+	const int   numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries */
+	int         i,j;
+	int         approximation;
+	IssmDouble  viscosity,Jdet;
+	IssmDouble  stokesreconditioning;
+	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble  dw[3];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	IssmDouble  dbasis[3][6]; //for the six nodes of the penta
+	GaussPenta *gauss=NULL;
+
+	/*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);
+
+	/*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* vzmacayeal_input=inputs->GetInput(VzMacAyealEnum);   _assert_(vzmacayeal_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);
+		GetNodalFunctionsP1(&basis[0], gauss);
+		GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+
+		vzmacayeal_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]);
+
+		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];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingMacAyealStokesFriction{{{*/
+ElementVector* Penta::CreatePVectorCouplingMacAyealStokesFriction(void){
+
+	/*Constants*/
+	const int numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries*/
+	int         i,j;
+	int         approximation,analysis_type;
+	IssmDouble  Jdet,Jdet2d;
+	IssmDouble  stokesreconditioning;
+	IssmDouble	bed_normal[3];
+	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble  viscosity, w, alpha2_gauss;
+	IssmDouble  dw[3];
+	IssmDouble	xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	Tria*       tria=NULL;
+	Friction*   friction=NULL;
+	GaussPenta  *gauss=NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	if(!IsOnBed() || IsFloating()) return NULL;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=MacAyealStokesApproximationEnum) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*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);
+
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*build friction object, used later on: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		vzmacayeal_input->GetInputValue(&w, gauss);
+		vzmacayeal_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]);
+		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];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingPattynStokes {{{*/
+ElementVector* Penta::CreatePVectorCouplingPattynStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorCouplingPattynStokesViscous();
+	ElementVector* pe2=CreatePVectorCouplingPattynStokesFriction();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingPattynStokesViscous {{{*/
+ElementVector* Penta::CreatePVectorCouplingPattynStokesViscous(void){
+
+	/*Constants*/
+	const int   numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries */
+	int         i;
+	int         approximation;
+	IssmDouble  viscosity,Jdet;
+	IssmDouble  stokesreconditioning;
+	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble  dw[3];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	IssmDouble  dbasis[3][6]; //for the six nodes of the penta
+	GaussPenta *gauss=NULL;
+
+	/*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);
+
+	/*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);
+
+	/* 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(&basis[0], gauss);
+		GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+
+		vzpattyn_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]);
+
+		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];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingPattynStokesFriction{{{*/
+ElementVector* Penta::CreatePVectorCouplingPattynStokesFriction(void){
+
+	/*Constants*/
+	const int numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries*/
+	int         i,j;
+	int         approximation,analysis_type;
+	IssmDouble  Jdet,Jdet2d;
+	IssmDouble  stokesreconditioning;
+	IssmDouble	bed_normal[3];
+	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble  viscosity, w, alpha2_gauss;
+	IssmDouble  dw[3];
+	IssmDouble	xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	Tria*       tria=NULL;
+	Friction*   friction=NULL;
+	GaussPenta  *gauss=NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	if(!IsOnBed() || IsFloating()) return NULL;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=PattynStokesApproximationEnum) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*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* vzpattyn_input=inputs->GetInput(VzPattynEnum);   _assert_(vzpattyn_input);
+
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*build friction object, used later on: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		vzpattyn_input->GetInputValue(&w, gauss);
+		vzpattyn_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]);
+		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];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticHoriz{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreatePVectorDiagnosticMacAyeal();
+		case PattynApproximationEnum:
+			return CreatePVectorDiagnosticPattyn();
+		case L1L2ApproximationEnum:
+			return CreatePVectorDiagnosticL1L2();
+		case HutterApproximationEnum:
+			return NULL;
+		case NoneApproximationEnum:
+			return NULL;
+		case StokesApproximationEnum:
+			return CreatePVectorDiagnosticStokes();
+		case MacAyealPattynApproximationEnum:
+			return CreatePVectorDiagnosticMacAyealPattyn();
+		case MacAyealStokesApproximationEnum:
+			return CreatePVectorDiagnosticMacAyealStokes();
+		case PattynStokesApproximationEnum:
+			return CreatePVectorDiagnosticPattynStokes();
+		default:
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticMacAyealPattyn{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticMacAyealPattyn(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticMacAyeal();
+	ElementVector* pe2=CreatePVectorDiagnosticPattyn();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticMacAyealStokes{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticMacAyealStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticMacAyeal();
+	ElementVector* pe2=CreatePVectorDiagnosticStokes();
+	ElementVector* pe3=CreatePVectorCouplingMacAyealStokes();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticPattynStokes{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticPattynStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticPattyn();
+	ElementVector* pe2=CreatePVectorDiagnosticStokes();
+	ElementVector* pe3=CreatePVectorCouplingPattynStokes();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticHutter{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticHutter(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;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	n=material->GetN();
+	B=material->GetB();
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);  _assert_(thickness_input);
+	Input* surface_input=inputs->GetInput(SurfaceEnum);      _assert_(surface_input);
+	Input* slopex_input=inputs->GetInput(SurfaceSlopeXEnum); _assert_(slopex_input);
+	Input* slopey_input=inputs->GetInput(SurfaceSlopeYEnum); _assert_(slopey_input);
+	for(i=0;i<NUMVERTICES;i++)z_list[i]=xyz_list[i][2];
+
+	/*Loop on the three segments*/
+	for(i=0;i<3;i++){
+		node0=i;
+		node1=i+3;
+
+		for(j=0;j<3;j++){
+			xyz_list_segment[0][j]=xyz_list[node0][j];
+			xyz_list_segment[1][j]=xyz_list[node1][j];
+		}
+
+		connectivity[0]=nodes[node0]->GetConnectivity();
+		connectivity[1]=nodes[node1]->GetConnectivity();
+
+		/*Loop on the Gauss points: */
+		gauss=new GaussPenta(node0,node1,3);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+
+			slopex_input->GetInputValue(&slope[0],gauss);
+			slopey_input->GetInputValue(&slope[1],gauss);
+			surface_input->GetInputValue(&surface,gauss);
+			thickness_input->GetInputValue(&thickness,gauss);
+
+			slope2=pow(slope[0],2)+pow(slope[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];
+			}
+			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];
+			}
+		}
+		delete gauss;
+
+		//Deal with lower surface
+		if (IsOnBed()){
+			constant_part=-1.58*pow((IssmDouble)10.0,-(IssmDouble)10.0)*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];
+		}
+	}
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticMacAyeal{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticMacAyeal(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();
+	delete tria->material; delete tria;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticL1L2{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticL1L2(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();
+	delete tria->material; delete tria;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticPattyn{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticPattyn(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int         i,j;
+	IssmDouble  Jdet;
+	IssmDouble  slope[3]; //do not put 2! this goes into GetInputDerivativeValue, which addresses slope[3] also!
+	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);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* surface_input=inputs->GetInput(SurfaceEnum);     _assert_(surface_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+
+		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];
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	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);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticStokesViscous {{{*/
+ElementVector* Penta::CreatePVectorDiagnosticStokesViscous(void){
+
+	/*Constants*/
+	const int numdofbubble=NDOF4*NUMVERTICES+NDOF3*1;
+
+	/*Intermediaries*/
+	int        i,j;
+	int        approximation;
+	IssmDouble Jdet,viscosity;
+	IssmDouble gravity,rho_ice,stokesreconditioning;
+	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);
+
+	/*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);
+
+	/* 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);
+		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]);
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticStokesShelf{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticStokesShelf(void){
+
+	/*Intermediaries*/
+	int         i,j;
+	int         approximation,shelf_dampening;
+	IssmDouble  gravity,rho_water,bed,water_pressure;
+	IssmDouble  damper,normal_vel,vx,vy,vz,dt;
+	IssmDouble	xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble	bed_normal[3];
+	IssmDouble  dz[3];
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	IssmDouble  Jdet2d;
+	GaussPenta  *gauss=NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	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);
+
+	/*Retrieve all inputs and parameters*/
+	rho_water=matpar->GetRhoWater();
+	gravity=matpar->GetG();
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* bed_input=inputs->GetInput(BedEnum); _assert_(bed_input);
+	Input* vx_input=inputs->GetInput(VxEnum);   _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);   _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);   _assert_(vz_input);
+
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		BedNormal(&bed_normal[0],xyz_list_tria);
+		bed_input->GetInputValue(&bed, gauss);
+		if(shelf_dampening){ //add dampening to avoid too high vertical velocities when not in hydrostatic equilibrium
+			bed_input->GetInputDerivativeValue(&dz[0],&xyz_list[0][0],gauss);
+			vx_input->GetInputValue(&vx, gauss);
+			vy_input->GetInputValue(&vy, gauss);
+			vz_input->GetInputValue(&vz, gauss);
+			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;
+		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];
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticVert {{{*/
+ElementVector* Penta::CreatePVectorDiagnosticVert(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticVertVolume();
+	ElementVector* pe2=CreatePVectorDiagnosticVertBase();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticVertVolume {{{*/
+ElementVector* Penta::CreatePVectorDiagnosticVertVolume(void){
+
+	/*Constants*/
+	const int  numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries*/
+	int        approximation;
+	IssmDouble     Jdet;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     dudx,dvdy,dwdz;
+	IssmDouble     du[3],dv[3],dw[3];
+	IssmDouble     basis[6];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	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);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		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);
+			dwdz=dw[2];
+		}
+		else dwdz=0;
+		dudx=du[0];
+		dvdy=dv[1];
+
+		for(int i=0;i<numdof;i++) pe->values[i] += (dudx+dvdy+dwdz)*Jdet*gauss->weight*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticVertBase {{{*/
+ElementVector* Penta::CreatePVectorDiagnosticVertBase(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j;
+	int        approximation;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble Jdet2d;
+	IssmDouble vx,vy,vz,dbdx,dbdy,basalmeltingvalue;
+	IssmDouble slope[3];
+	IssmDouble basis[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	if (!IsOnBed()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	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];
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	Input* bed_input=inputs->GetInput(BedEnum);                                _assert_(bed_input);
+	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum); _assert_(basal_melting_input);
+	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);
+	}
+
+	/* 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);
+
+		basal_melting_input->GetInputValue(&basalmeltingvalue, gauss);
+		bed_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+		vx_input->GetInputValue(&vx, gauss);
+		vy_input->GetInputValue(&vy, gauss);
+		if(approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
+			vzstokes_input->GetInputValue(&vz, gauss);
+		}
+		else vz=0;
+
+		dbdx=slope[0];
+		dbdy=slope[1];
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		for(i=0;i<numdof;i++) pe->values[i]+=-Jdet2d*gauss->weight*(vx*dbdx+vy*dbdy-vz-basalmeltingvalue)*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianDiagnosticHoriz{{{*/
+ElementMatrix* Penta::CreateJacobianDiagnosticHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreateJacobianDiagnosticMacayeal2d();
+		case PattynApproximationEnum:
+			return CreateJacobianDiagnosticPattyn();
+		case StokesApproximationEnum:
+			return CreateJacobianDiagnosticStokes();
+		case NoneApproximationEnum:
+			return NULL;
+		default:
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianDiagnosticMacayeal2d{{{*/
+ElementMatrix* Penta::CreateJacobianDiagnosticMacayeal2d(void){
+
+	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
+	  bedrock, in which case we spawn a tria element using the 3 first nodes, and use it to build 
+	  the stiffness matrix. */
+	if (!IsOnBed()) return NULL;
+
+	/*Depth average some fields*/
+	switch(this->material->ObjectEnum()){
+		case MaticeEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			break;
+		case MatdamageiceEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			this->InputDepthAverageAtBase(MaterialsRheologyZEnum,MaterialsRheologyZbarEnum,MaterialsEnum);
+			break;
+		default:
+			_error_("material "<<EnumToStringx(this->material->ObjectEnum())<<" not supported");
+	}
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateJacobianDiagnosticMacayeal();
+	delete tria->material; delete tria;
+
+	/*Delete averaged inputs*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->material->inputs->DeleteInput(MaterialsRheologyZbarEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianDiagnosticPattyn{{{*/
+ElementMatrix* Penta::CreateJacobianDiagnosticPattyn(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet;
+	IssmDouble eps1dotdphii,eps1dotdphij;
+	IssmDouble eps2dotdphii,eps2dotdphij;
+	IssmDouble mu_prime;
+	IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble eps1[3],eps2[3];
+	IssmDouble dphi[3][NUMVERTICES];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Jacobian with regular Pattyn (first part of the Gateau derivative)*/
+	ElementMatrix* Ke=CreateKMatrixDiagnosticPattyn();
+
+	/*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);
+
+	/* 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);
+		GetNodalFunctionsP1Derivatives(&dphi[0][0],&xyz_list[0][0],gauss);
+
+		this->GetStrainRate3dPattyn(&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];
+		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
+		eps1[2]=epsilon[3];                eps2[2]=epsilon[4];
+
+		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];
+
+				Ke->values[12*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[12*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[12*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[12*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianDiagnosticStokes{{{*/
+ElementMatrix* Penta::CreateJacobianDiagnosticStokes(void){
+
+	/*Constants*/
+	const int    numdof=NDOF4*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet;
+	IssmDouble eps1dotdphii,eps1dotdphij;
+	IssmDouble eps2dotdphii,eps2dotdphij;
+	IssmDouble eps3dotdphii,eps3dotdphij;
+	IssmDouble mu_prime;
+	IssmDouble epsilon[5]; /* epsilon=[exx,eyy,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();
+
+	/*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);
+
+	/* 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);
+		GetNodalFunctionsP1Derivatives(&dphi[0][0],&xyz_list[0][0],gauss);
+
+		this->GetStrainRate3dPattyn(&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];
+		eps1[1]=epsilon[2];   eps2[1]=epsilon[1];   eps3[1]=epsilon[4];
+		eps1[2]=epsilon[3];   eps2[2]=epsilon[4];   eps3[2]= -epsilon[0] -epsilon[1];
+
+		for(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;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticHoriz{{{*/
+void  Penta::GetSolutionFromInputsDiagnosticHoriz(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int         i;
+	int         approximation;
+	int        *doflist        = NULL;
+	IssmDouble  vx,vy;
+	IssmDouble  values[numdof];
+	GaussPenta *gauss;
+
+	/*Get approximation enum and dof list: */
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	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*/
+	GetDofList(&doflist,approximation,GsetEnum);
+
+	/*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++){
+
+		/*Recover vx and vy*/
+		gauss->GaussVertex(i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticHutter{{{*/
+void  Penta::GetSolutionFromInputsDiagnosticHutter(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble       vx,vy;
+	IssmDouble       values[numdof];
+	GaussPenta*  gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*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++){
+		/*Recover vx and vy*/
+		gauss->GaussVertex(i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticVert{{{*/
+void  Penta::GetSolutionFromInputsDiagnosticVert(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble       vz;
+	IssmDouble       values[numdof];
+	GaussPenta*  gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
+
+	/*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++){
+		/*Recover vz */
+		gauss->GaussVertex(i);
+		vz_input->GetInputValue(&vz,gauss);
+		values[i]=vz;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*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;
+
+	/*Get dof list: */
+	GetDofList(&doflist,StokesApproximationEnum,GsetEnum);
+	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* 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);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vz_input->GetInputValue(&vz,gauss);
+		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;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetL1L2Viscosity{{{*/
+void Penta::GetL1L2Viscosity(IssmDouble* pviscosity,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input,Input* surface_input){
+	/*Compute the L1L2 viscosity
+	 *
+	 *      1
+	 * mu = - A^-1 (sigma'_e)^(1-n)
+	 *      2
+	 *
+	 * sigma'_e^2 = |sigma'_//|^2 + |sigma'_perp|^2 (see Perego 2012 eq. 17,18)
+	 *
+	 * L1L2 assumptions:
+	 *
+	 * (1) |eps_b|_// = A (|sigma'_//|^2 + |sigma'_perp|^2)^((n-1)/2) |sigma'_//|
+	 * (2) |sigma'_perp|^2 = |rho g (s-z) grad(s)|^2
+	 *
+	 * Assuming that n = 3, we have a polynom of degree 3 to solve (the only unkown is X=|sigma'_//|)
+	 *
+	 * A X^3 + A |rho g (s-z) grad(s)|^2 X - |eps_b|_// = 0     */
+
+	int        i;
+	IssmDouble z,s,viscosity,p,q,delta;
+	IssmDouble tau_perp,tau_par,eps_b,A;
+	IssmDouble epsilonvx[5]; /*exx eyy exy exz eyz*/
+	IssmDouble epsilonvy[5]; /*exx eyy exy exz eyz*/
+	IssmDouble epsilon[5];   /*exx eyy exy exz eyz*/
+	IssmDouble z_list[NUMVERTICES];
+	IssmDouble slope[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input || !surface_input) _error_("Input missing");
+
+	/*Get tau_perp*/
+	for(i=0;i<NUMVERTICES;i++) z_list[i]=xyz_list[3*i+2];
+	surface_input->GetInputValue(&s,gauss);
+	surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+	PentaRef::GetInputValue(&z,&z_list[0],gauss);
+	tau_perp = matpar->GetRhoIce() * matpar->GetG() * fabs(s-z)*sqrt(slope[0]*slope[0]+slope[1]*slope[1]);
+
+	/* Get eps_b*/
+	vx_input->GetVxStrainRate3dPattyn(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3dPattyn(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]);
+	if(eps_b==0.){
+		*pviscosity = 2.5e+17;
+		return;
+	}
+
+	/*Get A*/
+	_assert_(material->GetN()==3.0);
+	A=material->GetA();
+
+	/*Solve for tau_perp (http://fr.wikipedia.org/wiki/Méthode_de_Cardan)*/
+	p     = tau_perp *tau_perp;
+	q     = - eps_b/A;
+	delta = q *q + p*p*p*4./27.;
+	_assert_(delta>0);
+	tau_par = pow(0.5*(-q+sqrt(delta)),1./3.) - pow(0.5*(q+sqrt(delta)),1./3.);
+
+	/*Viscosity*/
+	viscosity = 1./(2.*A*(tau_par*tau_par + tau_perp*tau_perp));
+	_assert_(!isnan(viscosity));
+	_assert_(viscosity > 0.);
+
+	/*Assign output pointer*/
+	*pviscosity = viscosity;
+	return; 
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHoriz {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticHoriz(IssmDouble* solution){
+
+	int  approximation;
+
+	/*Recover inputs*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*MacAyeal, everything is done by the element on bed*/
+	if (approximation==MacAyealApproximationEnum){
+		if (!IsOnBed()){
+			/*Do nothing. Element on bed will take care of it*/
+			return;
+		}
+		else{
+			InputUpdateFromSolutionDiagnosticMacAyeal(solution);
+			return;
+		}
+	}
+	if (approximation==L1L2ApproximationEnum){
+		if (!IsOnBed()) return;
+		InputUpdateFromSolutionDiagnosticL1L2(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){
+
+	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,MacAyealApproximationEnum,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::InputUpdateFromSolutionDiagnosticMacAyealPattyn {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticMacAyealPattyn(IssmDouble* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+	const int    numdof2d=NDOF2*NUMVERTICES2D;
+
+	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: */
+	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];
+
+		/*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 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>(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*/
+	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 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++){
+		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]];
+	}
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&macayeal_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]+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;
+
+		/*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* 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);
+	}
+	else{
+		_error_("Cannot update solution as VzMacAyeal is not present");
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<NUMVERTICES;i++) {
+		vz[i]=vzmacayeal[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));
+
+	/*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));
+
+	/*Free ressources:*/
+	xDelete<int>(doflistp);
+	xDelete<int>(doflists);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHutter {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticHutter(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,NoneApproximationEnum,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]];
+
+	/*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");
+	}
+
+	/*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 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::InputUpdateFromSolutionDiagnosticVert {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticVert(IssmDouble* solution){
+
+	const int numdof=NDOF1*NUMVERTICES;
+
+	int      i;
+	int      approximation;
+	IssmDouble   rho_ice,g;
+	IssmDouble   values[numdof];
+	IssmDouble   vx[NUMVERTICES];
+	IssmDouble   vy[NUMVERTICES];
+	IssmDouble   vz[NUMVERTICES];
+	IssmDouble   vzmacayeal[NUMVERTICES];
+	IssmDouble   vzpattyn[NUMVERTICES];
+	IssmDouble   vzstokes[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*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+		return;
+	}
+
+	/*Get dof list and vertices coordinates: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Use the dof list to index into the solution vector vz: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+	for(i=0;i<NUMVERTICES;i++){
+		vz[i]=values[i*NDOF1+0];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vz[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vx and Vy*/
+	GetInputListOnVertices(&vx[0],VxEnum,0.0); //default is 0
+	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");
+		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");
+		for(i=0;i<NUMVERTICES;i++){
+			vzmacayeal[i]=vz[i];
+			vz[i]=vzmacayeal[i]+vzstokes[i];
+		}
+	}
+
+	/*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: except it this is a PattynStokes element */
+	if(approximation!=PattynStokesApproximationEnum &&  approximation!=MacAyealStokesApproximationEnum){
+		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 Vz inputs to old 
+	 * status, otherwise, we'll wipe them off and add the new inputs: */
+	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
+
+	if(approximation!=PattynStokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum){
+		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));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*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;
+
+	/*Get dof list: */
+	GetDofList(&doflist,StokesApproximationEnum,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,NUMVERTICES,XYZPEnum);
+
+	/*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");
+		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);
+
+	/*Now, we have to move the previous 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(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_BALANCED_
+/*FUNCTION Penta::CreateKMatrixBalancethickness {{{*/
+ElementMatrix* Penta::CreateKMatrixBalancethickness(void){
+
+	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
+	  bedrock, in which case we spawn a tria element using the 3 first nodes, and use it to build 
+	  the stiffness matrix. */
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Spawn Tria element from the base of the Penta: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixBalancethickness();
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorBalancethickness {{{*/
+ElementVector* Penta::CreatePVectorBalancethickness(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorBalancethickness();
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_HYDROLOGY_
+/*FUNCTION Penta::CreateKMatrixHydrologyDCInefficient {{{*/
+ElementMatrix* Penta::CreateKMatrixHydrologyDCInefficient(void){
+
+	if (!IsOnBed()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixHydrologyDCInefficient();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixHydrologyDCEfficient {{{*/
+ElementMatrix* Penta::CreateKMatrixHydrologyDCEfficient(void){
+
+	if (!IsOnBed()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixHydrologyDCEfficient();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorHydrologyDCInefficient {{{*/
+ElementVector* Penta::CreatePVectorHydrologyDCInefficient(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->CreatePVectorHydrologyDCInefficient();
+	delete tria->material; delete tria;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorHydrologyDCEfficient {{{*/
+ElementVector* Penta::CreatePVectorHydrologyDCEfficient(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->CreatePVectorHydrologyDCEfficient();
+	delete tria->material; delete tria;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::GetHydrologyDCInefficientHmax{{{*/
+void  Penta::GetHydrologyDCInefficientHmax(IssmDouble* ph_max, Node* innode){
+
+	if (!IsOnBed()) return;
+	
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	tria->GetHydrologyDCInefficientHmax(ph_max,innode);
+	delete tria->material; delete tria;
+}
+/*}}}*/
+/*FUNCTION Penta::GetHydrologyTransfer{{{*/
+void  Penta::GetHydrologyTransfer(Vector<IssmDouble>* transfer){
+
+	if (!IsOnBed()) return;
+	
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	tria->GetHydrologyTransfer(transfer);
+	delete tria->material; delete tria;
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsOneDof {{{*/
+void Penta::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble   values[numdof];
+	IssmDouble   enum_value;
+	GaussPenta   *gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
+
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover temperature*/
+		gauss->GaussVertex(i);
+		enum_input->GetInputValue(&enum_value,gauss);
+		values[i]=enum_value;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::HydrologyEPLGetActive {{{*/
+void Penta::HydrologyEPLGetActive(Vector<IssmDouble>* active_vec){
+
+	if (!IsOnBed())return;
+	
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	tria->HydrologyEPLGetActive(active_vec);
+	delete tria->material; delete tria;
+
+}
+/*}}}*/
+/*FUNCTION Penta::HydrologyEPLGetMask{{{*/
+void  Penta::HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask){
+
+	if (!IsOnBed())return;
+	
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	tria->HydrologyEPLGetMask(vec_mask);
+	delete tria->material; delete tria;
+	
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionHydrologyDCInefficient{{{*/
+void  Penta::InputUpdateFromSolutionHydrologyDCInefficient(IssmDouble* solution){
+
+	const int   numdof   = NDOF1*NUMVERTICES;
+	const int   numdof2d = NDOF1*NUMVERTICES2D;
+	int*        doflist  = NULL;
+	bool        converged;
+	IssmDouble  values[numdof];
+	IssmDouble  residual[numdof];
+	IssmDouble  penalty_factor;
+	IssmDouble  kmax, kappa, h_max;
+	Penta      *penta    = NULL;
+
+	/*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(int i=0;i<numdof2d;i++){
+		values[i]         =solution[doflist[i]];
+		values[i+numdof2d]=values[i];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*If converged keep the residual in mind*/
+	this->inputs->GetInputValue(&converged,ConvergedEnum);
+
+	/*Get inputs*/
+	if(converged){
+		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.	
+		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);
+			}
+			else{
+				residual[i]=0.0;
+			}
+		}
+		delete tria->material; delete tria;
+	}
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+		/*Add input to the element: */
+		penta->inputs->AddInput(new PentaP1Input(SedimentHeadEnum,values));
+		penta->inputs->AddInput(new PentaP1Input(SedimentHeadResidualEnum,residual));
+
+		/*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);
+}
+/*}}}*/
+#endif
+
+#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];
+
+	if(!IsOnBed()) return;
+
+	/*Recover info at the vertices: */
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&gl_melting_rate,GroundinglineMeltingRateEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	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;
+
+	/*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));
+			}
+		}
+		/*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{
+			bed_hydro=-density*h[i];
+			if (bed_hydro>ba[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));
+				}
+				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) _error_("Error: migration should be Aggressive, Soft or Subelement");
+				}
+			}
+		}
+	}
+
+	/*SubelementMigrationEnum: if one grounded, all grounded*/
+	if(migration_style==SubelementMigrationEnum){
+		for(i=0;i<NUMVERTICES;i++){
+			if(nodes[i]->IsGrounded()){
+				groundedelement=true;
+				break;
+			}
+		}
+		floatingelement=!groundedelement;
+	}
+	else{
+		for(i=0;i<NUMVERTICES;i++){
+			if(nodes[i]->IsFloating()){
+				floatingelement=true;
+				break;
+			}
+		}
+	}
+
+   /*Add basal melting rate if element just ungrounded*/
+	if(!this->IsFloating() && floatingelement==true){
+		for(i=0;i<NUMVERTICES;i++)melting[i]=gl_melting_rate/yts;
+		this->inputs->AddInput(new PentaP1Input(BasalforcingsMeltingRateEnum,&melting[0]));
+	} 
+
+	/*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);
+	}
+
+	/*Extrude inputs*/
+	this->InputExtrude(SurfaceEnum,ElementEnum);
+	this->InputExtrude(BedEnum,ElementEnum);
+	this->InputExtrude(MaskElementonfloatingiceEnum,ElementEnum);
+	this->InputExtrude(MaskVertexonfloatingiceEnum,NodeEnum);
+	this->InputExtrude(MaskVertexongroundediceEnum,NodeEnum);
+}
+/*}}}*/
+/*FUNCTION Penta::PotentialUngrounding{{{*/
+void  Penta::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){
+
+	int     i;
+	IssmDouble  h[NUMVERTICES],ba[NUMVERTICES];
+	IssmDouble  bed_hydro;
+	IssmDouble  rho_water,rho_ice,density;
+
+	/*material parameters: */
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	density=rho_ice/rho_water;
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&ba[0],BathymetryEnum);
+
+	/*go through vertices, and figure out which ones are on the ice sheet, and want to unground: */
+	for(i=0;i<NUMVERTICES;i++){
+		/*Find if grounded vertices want to start floating*/
+		if (!nodes[i]->IsFloating()){
+			bed_hydro=-density*h[i];
+			if (bed_hydro>ba[i]){
+				/*Vertex that could potentially unground, flag it*/
+				potential_ungrounding->SetValue(nodes[i]->Sid(),1,INS_VAL);
+			}
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::UpdatePotentialUngrounding{{{*/
+int Penta::UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){
+
+	int i;
+	int nflipped=0;
+
+	/*Go through nodes, and whoever is on the potential_ungrounding, ends up in nodes_on_iceshelf: */
+	for(i=0;i<NUMVERTICES;i++){
+		if (reCast<bool,IssmDouble>(vertices_potentially_ungrounding[nodes[i]->Sid()])){
+			vec_nodes_on_iceshelf->SetValue(nodes[i]->Sid(),1,INS_VAL);
+
+			/*If node was not on ice shelf, we flipped*/
+			if(nodes_on_iceshelf[nodes[i]->Sid()]==0){
+				nflipped++;
+			}
+		}
+	}
+	return nflipped;
+}
+/*}}}*/
+#endif
Index: /issm/trunk/src/c/classes/Elements/Penta.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Penta.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/Penta.h	(revision 15396)
@@ -0,0 +1,349 @@
+/*! \file Penta.h 
+ *  \brief: header file for penta object
+ */
+
+#ifndef _PENTA_H_
+#define _PENTA_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Element.h"
+#include "./ElementHook.h"
+#include "./PentaRef.h"
+class Object;
+class Parameters;
+class Results;
+class Inputs;
+class Input;
+class IoModel;
+class Node;
+class Material;
+class Matpar;
+class Tria;
+class ElementMatrix;
+class ElementVector;
+
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/Enum/Enum.h"
+/*}}}*/
+
+class Penta: public Element,public ElementHook,public PentaRef{
+
+	public:
+
+		int          id;
+		int          sid;
+
+		Node       **nodes;                       // set of nodes
+		Vertex     **vertices;                    // 6 vertices
+		Material    *material;                    // 1 material ice
+		Matpar      *matpar;                      // 1 material parameter
+		Penta      **verticalneighbors;           // 2 neighbors: first one under, second one above
+		int          horizontalneighborsids[3];
+
+		Parameters  *parameters;                  //pointer to solution parameters
+		Inputs      *inputs;
+		Results     *results;
+
+		/*Penta constructors and destructor: {{{*/
+		Penta();
+		Penta(int penta_id,int penta_sid,int i, IoModel* iomodel,int nummodels);
+		~Penta();
+		/*}}}*/
+		/*Object virtual functions definitions: {{{*/
+		Object *copy();
+		void    DeepEcho();
+		void    Echo();
+		int     ObjectEnum();
+		int     Id();
+		/*}}}*/
+		/*Update virtual functions definitions: {{{*/
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromConstant(IssmDouble constant, int name);
+		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
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		/*}}}*/
+		/*Element virtual functions definitions: {{{*/
+		void   BasalFrictionCreateInput(void);
+		void   ComputeBasalStress(Vector<IssmDouble>* sigma_b);
+		void   ComputeStrainRate(Vector<IssmDouble>* eps);
+		void   ComputeStressTensor();
+		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   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);
+		void   DeleteResults(void);
+		int    GetNodeIndex(Node* node);
+		void   GetNodesSidList(int* sidlist);
+		int    GetNumberOfNodes(void);
+		void   GetSolutionFromInputs(Vector<IssmDouble>* solution);
+		IssmDouble GetZcoord(GaussPenta* gauss);
+		void   GetVectorFromInputs(Vector<IssmDouble>* vector,int name_enum);
+		void   GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int name_enum,int interp);
+
+		int    Sid();
+		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   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   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm);
+		void   ResetCoordinateSystem(void);
+		void   SmbGradients();
+		IssmDouble SurfaceArea(void);
+		void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type);
+		int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
+		IssmDouble TimeAdapt();
+		int*   GetHorizontalNeighboorSids(void);
+		void   ViscousHeatingCreateInput(void);
+
+		 #ifdef _HAVE_RESPONSES_
+		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);
+		IssmDouble MassFlux(IssmDouble* segment);
+		void   MaxAbsVx(IssmDouble* pmaxabsvx);
+		void   MaxAbsVy(IssmDouble* pmaxabsvy);
+		void   MaxAbsVz(IssmDouble* pmaxabsvz);
+		void   MaxVel(IssmDouble* pmaxvel);
+		void   ElementResponse(IssmDouble* presponse,int response_enum);
+		void   MaxVx(IssmDouble* pmaxvx);
+		void   MaxVy(IssmDouble* pmaxvy);
+		void   MaxVz(IssmDouble* pmaxvz);
+		#endif
+
+		#ifdef _HAVE_GIA_
+		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y);
+		#endif
+
+		#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   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   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);
+		IssmDouble SurfaceAbsVelMisfit(    int weight_index);
+		IssmDouble SurfaceRelVelMisfit(    int weight_index);
+		IssmDouble SurfaceLogVelMisfit(    int weight_index);
+		IssmDouble SurfaceLogVxVyMisfit(   int weight_index);
+		IssmDouble SurfaceAverageVelMisfit(int weight_index);
+		IssmDouble ThicknessAbsGradient(int weight_index);
+		IssmDouble ThicknessAlongGradient( int weight_index){_error_("not supported");};
+		IssmDouble ThicknessAcrossGradient(int weight_index){_error_("not supported");};
+		IssmDouble BalancethicknessMisfit(int weight_index){_error_("not supported");};
+		void   InputControlUpdate(IssmDouble scalar,bool save_parameter);
+		#endif
+		
+		#ifdef _HAVE_GROUNDINGLINE_
+		void   MigrateGroundingLine(IssmDouble* old_floating_ice,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);
+		#endif
+
+		/*}}}*/
+		/*Penta specific routines:{{{*/
+		void	  BedNormal(IssmDouble* bed_normal, IssmDouble xyz_list[3][3]);
+		ElementMatrix* CreateBasalMassMatrix(void);
+		ElementMatrix* CreateKMatrixPrognostic(void);
+		ElementVector* CreatePVectorPrognostic(void);
+		ElementVector* CreatePVectorSlope(void);
+		void	         GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	         GetVertexPidList(int* doflist);
+		void           GetVertexSidList(int* sidlist);
+		void           GetConnectivityList(int* connectivity);
+		IssmDouble     GetGroundedPortion(IssmDouble* xyz_list);
+		int            GetElementType(void);
+		void           GetElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
+		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype);
+		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
+		void           GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
+		void	         GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity);
+		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);
+		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*);
+		#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);
+		#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);
+		void    GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type);
+		void    HydrologyEPLGetActive(Vector<IssmDouble>* active_vec);
+		void    HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask);
+		void    InputUpdateFromSolutionHydrologyDCInefficient(IssmDouble* solution);
+		#endif
+		#ifdef _HAVE_THERMAL_
+		ElementMatrix* CreateKMatrixEnthalpy(void);
+		ElementMatrix* CreateKMatrixEnthalpyVolume(void);
+		ElementMatrix* CreateKMatrixEnthalpyShelf(void);
+		ElementMatrix* CreateKMatrixThermal(void);
+		ElementMatrix* CreateKMatrixMelting(void);
+		ElementMatrix* CreateKMatrixThermalVolume(void);
+		ElementMatrix* CreateKMatrixThermalShelf(void);
+		ElementVector* CreatePVectorEnthalpy(void);
+		ElementVector* CreatePVectorEnthalpyVolume(void);
+		ElementVector* CreatePVectorEnthalpyShelf(void);
+		ElementVector* CreatePVectorEnthalpySheet(void);
+		ElementVector* CreatePVectorMelting(void);
+		ElementVector* CreatePVectorThermal(void);
+		ElementVector* CreatePVectorThermalVolume(void);
+		ElementVector* CreatePVectorThermalShelf(void);
+		ElementVector* CreatePVectorThermalSheet(void);
+		void	       GetSolutionFromInputsThermal(Vector<IssmDouble>* solutiong);
+		void           InputUpdateFromSolutionThermal( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionEnthalpy( IssmDouble* solutiong);
+		#endif
+		#ifdef _HAVE_BALANCED_
+		ElementMatrix* CreateKMatrixBalancethickness(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		#endif
+		/*}}}*/
+};
+#endif  /* _PENTA_H */
Index: /issm/trunk/src/c/classes/Elements/PentaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 15396)
@@ -0,0 +1,1399 @@
+/*!\file PentaRef.c
+ * \brief: implementation of the PentaRef 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"
+/*}}}*/
+
+/*Element macros*/
+#define NUMNODESP1    6
+#define NUMNODESP1_2d 3
+#define NUMNODESMINI  7
+
+/*Object constructors and destructor*/
+/*FUNCTION PentaRef::PentaRef(){{{*/
+PentaRef::PentaRef(){
+	this->element_type_list=NULL;
+}
+/*}}}*/
+/*FUNCTION PentaRef::PentaRef(int* types,int nummodels){{{*/
+PentaRef::PentaRef(const int nummodels){
+
+	/*Only allocate pointer*/
+	element_type_list=xNew<int>(nummodels);
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::~PentaRef(){{{*/
+PentaRef::~PentaRef(){
+	xDelete<int>(element_type_list);
+}
+/*}}}*/
+
+/*Management*/
+/*FUNCTION PentaRef::SetElementType{{{*/
+void PentaRef::SetElementType(int type,int type_counter){
+
+	_assert_(type==P1Enum || type==P1DGEnum);
+
+	/*initialize element type*/
+	this->element_type_list[type_counter]=type;
+}
+/*}}}*/
+
+/*Reference Element numerics*/
+/*FUNCTION PentaRef::GetBMacAyealPattyn {{{*/
+void PentaRef::GetBMacAyealPattyn(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
+	 * by: 
+	 *       Bi=[ dh/dx          0      ]
+	 *          [   0           dh/dy   ]
+	 *          [ 1/2*dh/dy  1/2*dh/dx  ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume 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);
+
+	/*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){
+	/*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
+	 * by: 
+	 *       Bi=[ dh/dx          0       0   0 ]
+	 *          [   0           dh/dy    0   0 ]
+	 *          [ 1/2*dh/dy  1/2*dh/dx   0   0 ]
+	 *          [   0            0       0   h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 */
+
+	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);
+
+	/*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){
+	/*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
+	 * by: 
+	 *       Bi=[ dh/dx          0      ]
+	 *          [   0           dh/dy   ]
+	 *          [ 1/2*dh/dy  1/2*dh/dx  ]
+	 *          [ 1/2*dh/dz      0      ]
+	 *          [  0         1/2*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);
+
+	/*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){
+	/*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    ]
+	 * 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);
+
+	/*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){
+	/*Compute Bprime  matrix. Bprime=[Bprime1 Bprime2 Bprime3 Bprime4 Bprime5 Bprime6] where Bprimei is of size 5*NDOF2. 
+	 * For node i, Bprimei can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bprimei=[ 2*dh/dx    dh/dy   0   0 ]
+	 *               [  dh/dx    2*dh/dy  0   0 ]
+	 *               [  dh/dy     dh/dx   0   0 ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume Bprime has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 */
+
+	int    i;
+	IssmDouble dh1dh7[3][NUMNODESMINI];
+
+	/*Get dh1dh6 in actual coordinate system: */
+	GetNodalFunctionsMINIDerivatives(&dh1dh7[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){
+
+	/*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  ]
+	 *					[   0           dh/dy           0       0  ]
+	 *					[   0             0           dh/dy     0  ]
+	 *					[ 1/2*dh/dy    1/2*dh/dx        0       0  ]
+	 *					[ 1/2*dh/dz       0         1/2*dh/dx   0  ]
+	 *					[   0          1/2*dh/dz    1/2*dh/dy   0  ]
+	 *					[   0             0             0       h  ]
+	 *					[ dh/dx         dh/dy         dh/dz     0  ]
+	 *	where h is the interpolation function for node i.
+	 *	Same thing for Bb except the last column that does not exist.
+	 */
+
+	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);
+
+	/*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){
+	/*	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: 
+	 *				Bi'=[  dh/dx   0          0       0]
+	 *					 [   0      dh/dy      0       0]
+	 *					 [   0      0         dh/dz    0]
+	 *					 [  dh/dy   dh/dx      0       0]
+	 *					 [  dh/dz   0        dh/dx     0]
+	 *					 [   0      dh/dz    dh/dy     0]
+	 *					 [  dh/dx   dh/dy    dh/dz     0]
+	 *					 [   0      0          0       h]
+	 *	where h is the interpolation function for node i.
+	 *
+	 * 	Same thing for the bubble fonction except that there is no fourth column
+	 */
+
+	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);
+
+	/*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];
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBAdvec{{{*/
+void PentaRef::GetBAdvec(IssmDouble* B_advec, IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_advec =[ h ]
+	 *                 [ h ]
+	 *                 [ h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
+	 */
+
+	/*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]; 
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBConduct{{{*/
+void PentaRef::GetBConduct(IssmDouble* B_conduct, IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_conduct=[ dh/dx ]
+	 *                  [ dh/dy ]
+	 *                  [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*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]; 
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBVert{{{*/
+void PentaRef::GetBVert(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss){
+	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
+		where hi is the interpolation function for node i.*/
+
+	int i;
+	IssmDouble dh1dh6[3][NUMNODESP1];
+
+	/*Get dh1dh6 in actual coordinate system: */
+	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list, gauss);
+
+	/*Build B: */
+	for (i=0;i<NUMNODESP1;i++){
+		B[i]=dh1dh6[2][i];  
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBprimeAdvec{{{*/
+void PentaRef::GetBprimeAdvec(IssmDouble* Bprime_advec, IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Biprime_advec=[ dh/dx ]
+	 *                     [ dh/dy ]
+	 *                     [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*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++){
+		*(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]; 
+	}
+}
+/*}}}*/
+/*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){
+	/*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
+	 ** by: 
+	 **                 Bi=[ N   0 ]
+	 **                    [ 0   N ]
+	 ** where N is the interpolation function for node i.
+	 **
+	 ** We assume B has been allocated already, of size: 2 (2 x numnodes)
+	 **/
+
+	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];
+	}
+} 
+/*}}}*/
+/*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. 
+	 * For node i, Li can be expressed in the actual coordinate system
+	 * by: 
+	 *       Li=[ h 0 ]
+	 *	 	      [ 0 h ]
+	 *		      [ 0 0 ]
+	 *		      [ 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. 
+	 * For node i, Lpi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Lpi=[ h    0    0   0]1
+	 *		       [ 0    h    0   0]2
+	 *		       [ h    0    0   0]3
+	 *		       [ 0    h    0   0]4
+	 *		       [ 0    0    h   0]5
+	 *		       [ 0    0    h   0]6
+	 *		       [ 0    0  dh/dz 0]7
+	 *		       [ 0    0  dh/dz 0]8
+	 *		       [ 0    0  dh/dz 0]9
+	 *		       [dh/dz 0  dh/dx 0]0
+	 *		       [ 0 dh/dz dh/dy 0]1
+	 *           [ 0    0    0   h]2
+	 *           [ 0    0    0   h]3
+	 *           [ 0    0    0   h]4
+	 *
+	 *       Li=[ h    0    0   0]1
+	 *	 	      [ 0    h    0   0]2
+	 *		      [ 0    0    h   0]3
+	 *		      [ 0    0    h   0]4
+	 *	 	      [ h    0    0   0]5
+	 *	 	      [ 0    h    0   0]6
+	 *	 	      [ h    0    0   0]7
+	 *	 	      [ 0    h    0   0]8
+	 *		      [ 0    0    h   0]9
+	 *		      [ 0    0    h   0]0
+	 *		      [ 0    0    h   0]1
+	 *	 	      [ h    0    0   0]2
+	 *	 	      [ 0    h    0   0]3
+	 *		      [ 0    0    h   0]4
+	 * 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)=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){
+	/*
+	 * 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 ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 * where h is the interpolation function for node i.
+	 */
+
+	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. 
+	 * For node i, Lpi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Lpi=[ h    0    0   0]
+	 *		       [ 0    h    0   0]
+	 *		       [ 0    0    h   0]
+	 *		       [ 0    0    h   0]
+	 *		       [ 0    0  dh/dz 0]
+	 *		       [ 0    0  dh/dz 0]
+	 *           [ 0    0    0   h]
+	 *           [ 0    0    0   h]
+	 * 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. 
+	 * 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]
+	 * 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. 
+	 * For node i, Lpi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Lpi=[ h    0 ]
+	 *		       [ 0    h ]
+	 *		       [ h    0 ]
+	 *		       [ 0    h ]
+	 * 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];
+	}
+}
+/*}}}*/
+/*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 x1,x2,x3,x4,x5,x6;
+	IssmDouble y1,y2,y3,y4,y5,y6;
+	IssmDouble z1,z2,z3,z4,z5,z6;
+
+	/*Figure out xi,eta and zi (parametric coordinates), for this gaussian point: */
+	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);
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetJacobianDeterminant {{{*/
+void PentaRef::GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussPenta* gauss){
+	/*On a penta, Jacobian varies according to coordinates. We need to get the Jacobian, and take 
+	 * the determinant of it: */
+	IssmDouble J[3][3];
+
+	/*Get Jacobian*/
+	GetJacobian(&J[0][0],xyz_list,gauss);
+
+	/*Get Determinant*/
+	Matrix3x3Determinant(Jdet,&J[0][0]);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetTriaJacobianDeterminant{{{*/
+void PentaRef::GetTriaJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussPenta* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1,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);
+
+	/*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);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetSegmentJacobianDeterminant{{{*/
+void PentaRef::GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussPenta* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1,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.));
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetJacobianInvert {{{*/
+void PentaRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussPenta* gauss){
+
+	/*Jacobian*/
+	IssmDouble J[3][3];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0], xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	Matrix3x3Invert(Jinv,&J[0][0]);
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctions{{{*/
+void PentaRef::GetNodalFunctions(IssmDouble* basis,GaussPenta* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(basis);
+
+	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.;
+			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);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsDerivatives{{{*/
+void PentaRef::GetNodalFunctionsDerivatives(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    Jinv[3][3];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives in reference triangle*/
+	IssmDouble* dbasis_ref=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivativesReference(dbasis_ref,gauss); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dbasis: 
+	 *
+	 * [dhi/dx]= Jinv'*[dhi/dr]
+	 * [dhi/dy]        [dhi/ds]
+	 * [dhi/dz]        [dhi/dzeta]
+	 */
+
+	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]+Jinv[0][2]*dbasis_ref[2*numnodes+i];
+		dbasis[numnodes*1+i]=Jinv[1][0]*dbasis_ref[0*numnodes+i]+Jinv[1][1]*dbasis_ref[1*numnodes+i]+Jinv[1][2]*dbasis_ref[2*numnodes+i];
+		dbasis[numnodes*2+i]=Jinv[2][0]*dbasis_ref[0*numnodes+i]+Jinv[2][1]*dbasis_ref[1*numnodes+i]+Jinv[2][2]*dbasis_ref[2*numnodes+i];
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsDerivativesReference{{{*/
+void PentaRef::GetNodalFunctionsDerivativesReference(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. */
+
+	_assert_(dbasis && gauss);
+
+	/*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;
+
+	switch(this->element_type){
+		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);
+			/*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);
+			/*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);
+			/*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);
+			/*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);
+			/*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:
+			/*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);
+			/*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);
+			/*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);
+			/*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);
+			/*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);
+			/*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);
+			/*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);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsMINI{{{*/
+void PentaRef::GetNodalFunctionsMINI(IssmDouble* l1l7, GaussPenta* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	l1l7[0]=gauss->coord1*(1.0-gauss->coord4)/2.0;
+	l1l7[1]=gauss->coord2*(1.0-gauss->coord4)/2.0;
+	l1l7[2]=gauss->coord3*(1.0-gauss->coord4)/2.0;
+	l1l7[3]=gauss->coord1*(1.0+gauss->coord4)/2.0;
+	l1l7[4]=gauss->coord2*(1.0+gauss->coord4)/2.0;
+	l1l7[5]=gauss->coord3*(1.0+gauss->coord4)/2.0;
+	l1l7[6]=27*gauss->coord1*gauss->coord2*gauss->coord3*(1.0+gauss->coord4)*(1.0-gauss->coord4);
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsMINIDerivatives{{{*/
+void PentaRef::GetNodalFunctionsMINIDerivatives(IssmDouble* dh1dh7,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    Jinv[3][3];
+
+	/*Get derivative values with respect to parametric coordinate system: */
+	GetNodalFunctionsMINIDerivativesReference(&dh1dh7_ref[0][0], gauss); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dh1dh6: 
+	 *
+	 * [dhi/dx]= Jinv'*[dhi/dr]
+	 * [dhi/dy]        [dhi/ds]
+	 * [dhi/dz]        [dhi/dzeta]
+	 */
+
+	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];
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsMINIDerivativesReference{{{*/
+void PentaRef::GetNodalFunctionsMINIDerivativesReference(IssmDouble* dl1dl7,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);
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsP1 {{{*/
+void PentaRef::GetNodalFunctionsP1(IssmDouble* l1l6, 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;
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsP1Derivatives {{{*/
+void PentaRef::GetNodalFunctionsP1Derivatives(IssmDouble* dh1dh6,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    Jinv[NDOF3][NDOF3];
+
+	/*Get derivative values with respect to parametric coordinate system: */
+	GetNodalFunctionsP1DerivativesReference(&dh1dh6_ref[0][0], gauss); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dh1dh3: 
+	 *
+	 * [dhi/dx]= Jinv*[dhi/dr]
+	 * [dhi/dy]       [dhi/ds]
+	 * [dhi/dz]       [dhi/dn]
+	 */
+
+	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];
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsP1DerivativesReference {{{*/
+void PentaRef::GetNodalFunctionsP1DerivativesReference(IssmDouble* dl1dl6,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;
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetQuadNodalFunctions {{{*/
+void PentaRef::GetQuadNodalFunctions(IssmDouble* l1l4,GaussPenta* gauss,int index1,int index2,int index3,int index4){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	IssmDouble BasisFunctions[6];
+
+	GetNodalFunctionsP1(&BasisFunctions[0],gauss);
+
+	_assert_(index1>=0 && index1<6);
+	_assert_(index2>=0 && index2<6);
+	_assert_(index3>=0 && index3<6);
+	_assert_(index4>=0 && index4<6);
+
+	l1l4[0]=BasisFunctions[index1];
+	l1l4[1]=BasisFunctions[index2];
+	l1l4[2]=BasisFunctions[index3];
+	l1l4[3]=BasisFunctions[index4];
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetQuadJacobianDeterminant{{{*/
+void PentaRef::GetQuadJacobianDeterminant(IssmDouble* Jdet,IssmDouble xyz_list[4][3],GaussPenta* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	IssmDouble x1,x2,x3,x4,y1,y2,y3,y4,z1,z2,z3,z4;
+
+	x1=xyz_list[0][0];
+	y1=xyz_list[0][1];
+	z1=xyz_list[0][2];
+	x2=xyz_list[1][0];
+	y2=xyz_list[1][1];
+	z2=xyz_list[1][2];
+	x3=xyz_list[2][0];
+	y3=xyz_list[2][1];
+	z3=xyz_list[2][2];
+	x4=xyz_list[3][0];
+	y4=xyz_list[3][1];
+	z4=xyz_list[3][2];
+
+	/*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!");
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetInputValue{{{*/
+void PentaRef::GetInputValue(IssmDouble* pvalue,IssmDouble* plist,GaussPenta* gauss){
+	/*P1 interpolation on Gauss point*/
+
+	/*intermediary*/
+	IssmDouble l1l6[6];
+
+	/*nodal functions: */
+	GetNodalFunctionsP1(&l1l6[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];
+
+}
+/*}}}*/
+/*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:
+	 *   dp/dx=p_list[0]*dh1/dx+p_list[1]*dh2/dx+p_list[2]*dh3/dx+p_list[3]*dh4/dx+p_list[4]*dh5/dx+p_list[5]*dh6/dx;
+	 *   dp/dy=p_list[0]*dh1/dy+p_list[1]*dh2/dy+p_list[2]*dh3/dy+p_list[3]*dh4/dy+p_list[4]*dh5/dy+p_list[5]*dh6/dy;
+	 *   dp/dz=p_list[0]*dh1/dz+p_list[1]*dh2/dz+p_list[2]*dh3/dz+p_list[3]*dh4/dz+p_list[4]*dh5/dz+p_list[5]*dh6/dz;
+	 *
+	 *   p is a vector of size 3x1 already allocated.
+	 */
+	IssmDouble dh1dh6[3][NUMNODESP1];
+
+	/*Get nodal funnctions derivatives in actual coordinate system: */
+	GetNodalFunctionsP1Derivatives(&dh1dh6[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];
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::NumberofNodes{{{*/
+int PentaRef::NumberofNodes(void){
+
+	switch(this->element_type){
+		case P1Enum:   return NUMNODESP1;
+		case MINIEnum: return NUMNODESMINI;
+		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/PentaRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/PentaRef.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/PentaRef.h	(revision 15396)
@@ -0,0 +1,66 @@
+/*!\file:  PentaRef.h
+ * \brief abstract class for handling Penta oriented routines, like nodal functions, 
+ * strain rate generation, etc ...
+ */ 
+
+#ifndef _PENTAREF_H_
+#define _PENTAREF_H_
+
+class GaussPenta;
+class PentaRef{
+
+	public: 
+		int* element_type_list; //P1CG, P1DG, MINI, P2...
+		int  element_type;
+
+		PentaRef();
+		PentaRef(const int nummodels);
+		~PentaRef();
+
+		/*Management*/
+		void SetElementType(int type,int type_counter);
+
+		/*Numerics*/
+		void GetNodalFunctions(IssmDouble* basis, GaussPenta* gauss);
+		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,GaussPenta* gauss);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussPenta* gauss);
+		void GetNodalFunctionsP1(IssmDouble* l1l6, GaussPenta* gauss);
+		void GetNodalFunctionsMINI(IssmDouble* l1l7, GaussPenta* gauss);
+		void GetNodalFunctionsP1Derivatives(IssmDouble* dh1dh6,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetNodalFunctionsMINIDerivatives(IssmDouble* dh1dh7,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetNodalFunctionsP1DerivativesReference(IssmDouble* dl1dl6,GaussPenta* gauss);
+		void GetNodalFunctionsMINIDerivativesReference(IssmDouble* dl1dl7,GaussPenta* gauss);
+		void GetQuadNodalFunctions(IssmDouble* l1l4,GaussPenta* gauss,int index1,int index2,int index3,int index4);
+		void GetQuadJacobianDeterminant(IssmDouble*  Jdet, IssmDouble xyz_list[4][3],GaussPenta* gauss);
+		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussPenta* gauss);
+		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussPenta* gauss);
+		void GetTriaJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussPenta* gauss);
+		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 GetBprimeVert(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBAdvec(IssmDouble* B_advec, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBConduct(IssmDouble* B_conduct, IssmDouble* xyz_list, GaussPenta* gauss);
+		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 GetInputValue(IssmDouble* pvalue,IssmDouble* plist, GaussPenta* gauss);
+		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist,GaussTria* gauss){_error_("only PentaGauss are supported");};
+		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, GaussTria* gauss){_error_("only PentaGauss are supported");};
+
+		int  NumberofNodes(void);
+};
+#endif
Index: /issm/trunk/src/c/classes/Elements/Tria.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 15396)
@@ -0,0 +1,7068 @@
+/*!\file Tria.cpp
+ * \brief: implementation of the Tria object
+ */
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../classes.h"
+#include "../../shared/shared.h"
+#ifdef _HAVE_GIA_
+#include "../../modules/GiaDeflectionCorex/GiaDeflectionCorex.h"
+#endif
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 3
+/*Constructors/destructor/copy*/
+/*FUNCTION Tria::Tria(){{{*/
+Tria::Tria(){
+	
+	int i;
+
+	this->nodes    = NULL;
+	this->vertices = NULL;
+	this->material = NULL;
+	this->matpar   = NULL;
+	for(i=0;i<3;i++)this->horizontalneighborsids[i]=UNDEF;
+	this->inputs     = NULL;
+	this->parameters = NULL;
+	this->results    = NULL;
+
+}
+/*}}}*/
+/*FUNCTION Tria::Tria(int id, int sid,int index, IoModel* iomodel,int nummodels){{{*/
+Tria::Tria(int tria_id, int tria_sid, int index, IoModel* iomodel,int nummodels)
+	:TriaRef(nummodels)
+	,ElementHook(nummodels,index+1,3,iomodel){
+
+		/*id: */
+		this->id=tria_id;
+		this->sid=tria_sid;
+
+		//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+		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();
+
+		/*initialize pointers:*/
+		this->nodes    = NULL;
+		this->vertices = NULL;
+		this->material = NULL;
+		this->matpar   = NULL;
+
+}
+/*}}}*/
+/*FUNCTION Tria::~Tria(){{{*/
+Tria::~Tria(){
+	delete inputs;
+	delete results;
+	this->parameters=NULL;
+}
+/*}}}*/
+/*FUNCTION Tria::copy {{{*/
+Object* Tria::copy() {
+
+	int i;
+	Tria* tria=NULL;
+
+	tria=new Tria();
+
+	//deal with TriaRef mother class
+	tria->element_type_list=xNew<int>(this->numanalyses);
+	for(i=0;i<this->numanalyses;i++) tria->element_type_list[i]=this->element_type_list[i];
+
+	//deal with ElementHook mother class
+	tria->numanalyses=this->numanalyses;
+	tria->hnodes=new Hook*[tria->numanalyses];
+	for(i=0;i<tria->numanalyses;i++)tria->hnodes[i]=(Hook*)this->hnodes[i]->copy();
+	tria->hvertices=(Hook*)this->hvertices->copy();
+	tria->hmaterial=(Hook*)this->hmaterial->copy();
+	tria->hmatpar=(Hook*)this->hmatpar->copy();
+
+	/*deal with Tria fields: */
+	tria->id=this->id;
+	tria->sid=this->sid;
+	if(this->inputs){
+		tria->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		tria->inputs=new Inputs();
+	}
+	if(this->results){
+		tria->results=(Results*)this->results->Copy();
+	}
+	else{
+		tria->results=new Results();
+	}
+	/*point parameters: */
+	tria->parameters=this->parameters;
+
+	/*recover objects: */
+	tria->nodes=xNew<Node*>(3); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+	for(i=0;i<3;i++)tria->nodes[i]=this->nodes[i];
+	tria->vertices=(Vertex**)tria->hvertices->deliverp();
+	tria->material=(Material*)tria->hmaterial->delivers();
+	tria->matpar=(Matpar*)tria->hmatpar->delivers();
+
+	/*neighbors: */
+	for(i=0;i<3;i++)tria->horizontalneighborsids[i]=this->horizontalneighborsids[i];
+
+	return tria;
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION Tria::SetwiseNodeConnectivity{{{*/
+void Tria::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<3;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 Tria::CreateKMatrix {{{*/
+void  Tria::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+
+	/*retreive parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging mode{{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->parameters && this->inputs);
+	/*}}}*/
+
+	/*Skip if water element*/
+	if(IsOnWater()) 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=CreateKMatrixDiagnosticMacAyeal();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticHutter();
+			break;
+		 #endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			Ke=CreateMassMatrix();
+			break;
+		case PrognosticAnalysisEnum:
+			Ke=CreateKMatrixPrognostic();
+			break;
+		#ifdef _HAVE_HYDROLOGY_
+		case HydrologyShreveAnalysisEnum:
+			Ke=CreateKMatrixHydrologyShreve();
+			break;
+		case HydrologyDCInefficientAnalysisEnum:
+			Ke=CreateKMatrixHydrologyDCInefficient();
+			break;
+		case HydrologyDCEfficientAnalysisEnum:
+			Ke=CreateKMatrixHydrologyDCEfficient();
+			break;
+		#endif
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		#endif
+		#ifdef _HAVE_CONTROL_
+		case AdjointBalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixAdjointBalancethickness();
+			break;
+		case AdjointHorizAnalysisEnum:
+			Ke=CreateKMatrixAdjointMacAyeal();
+			break;
+		#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*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);
+
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetNodalFunctions(&basis[0],gauss);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		D=gauss->weight*Jdet;
+
+		TripleMultiply(&basis[0],1,3,1,
+					&D,1,1,0,
+					&basis[0],1,3,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateDVector {{{*/
+void  Tria::CreateDVector(Vector<IssmDouble>* df){
+
+	/*Nothing done yet*/
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVector {{{*/
+void  Tria::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*retrive parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*asserts: {{{*/
+	/*if debugging mode, check that all pointers exist*/
+	_assert_(this->nodes && this->material && this->matpar && this->parameters && this->inputs);
+	/*}}}*/
+
+	/*Skip if water element*/
+	if(IsOnWater()) return;
+
+	/*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();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			pe=CreatePVectorDiagnosticHutter();
+			break;
+		#endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			pe=CreatePVectorSlope();
+			break;
+		case PrognosticAnalysisEnum:
+			pe=CreatePVectorPrognostic();
+			break;
+		#ifdef _HAVE_HYDROLOGY_
+		case HydrologyShreveAnalysisEnum:
+			pe=CreatePVectorHydrologyShreve();
+			break;
+		case HydrologyDCInefficientAnalysisEnum:
+			pe=CreatePVectorHydrologyDCInefficient();
+			break;
+		case HydrologyDCEfficientAnalysisEnum:
+			pe=CreatePVectorHydrologyDCEfficient();
+			break;
+		#endif
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			pe=CreatePVectorBalancethickness();
+			break;
+		#endif
+		#ifdef _HAVE_CONTROL_
+		case AdjointBalancethicknessAnalysisEnum:
+			pe=CreatePVectorAdjointBalancethickness();
+			break;
+		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 Tria::CreatePVectorSlope {{{*/
+ElementVector* Tria::CreatePVectorSlope(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i;
+	int        analysis_type;
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble slope[2];
+	IssmDouble basis[3];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* slope_input=NULL;
+	if ( (analysis_type==SurfaceSlopeXAnalysisEnum) || (analysis_type==SurfaceSlopeYAnalysisEnum)){
+		slope_input=inputs->GetInput(SurfaceEnum); _assert_(slope_input);
+	}
+	if ( (analysis_type==BedSlopeXAnalysisEnum) || (analysis_type==BedSlopeYAnalysisEnum)){
+		slope_input=inputs->GetInput(BedEnum);     _assert_(slope_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],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];
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateJacobianMatrix{{{*/
+void  Tria::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->parameters && this->inputs);
+	/*}}}*/
+
+	/*Skip if water element*/
+	if(IsOnWater()) 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();
+			break;
+#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Jff);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeBasalStress {{{*/
+void  Tria::ComputeBasalStress(Vector<IssmDouble>* eps){
+	_error_("Not Implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeStrainRate {{{*/
+void  Tria::ComputeStrainRate(Vector<IssmDouble>* eps){
+	_error_("Not Implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeStressTensor {{{*/
+void  Tria::ComputeStressTensor(){
+
+	IssmDouble      xyz_list[NUMVERTICES][3];
+	IssmDouble      pressure,viscosity;
+	IssmDouble      epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble      sigma_xx[NUMVERTICES];
+	IssmDouble		sigma_yy[NUMVERTICES];
+	IssmDouble		sigma_zz[NUMVERTICES]={0,0,0};
+	IssmDouble      sigma_xy[NUMVERTICES];
+	IssmDouble		sigma_xz[NUMVERTICES]={0,0,0};
+	IssmDouble		sigma_yz[NUMVERTICES]={0,0,0};
+	GaussTria* gauss=NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		material->GetViscosity2d(&viscosity,&epsilon[0]);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx[iv]=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
+		sigma_yy[iv]=2*viscosity*epsilon[1]-pressure;
+		sigma_xy[iv]=2*viscosity*epsilon[2];
+	}
+
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new TriaInput(StressTensorxxEnum,&sigma_xx[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(StressTensorxyEnum,&sigma_xy[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(StressTensorxzEnum,&sigma_xz[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(StressTensoryyEnum,&sigma_yy[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(StressTensoryzEnum,&sigma_yz[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(StressTensorzzEnum,&sigma_zz[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::Configure {{{*/
+void  Tria::Configure(Elements* elementsin, Loads* loadsin,Nodes* nodesin,Vertices *verticesin,Materials* materialsin, Parameters* parametersin){
+
+	/*go into parameters and get the analysis_counter: */
+	int analysis_counter;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*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: */
+	if(this->hnodes[analysis_counter]) this->hnodes[analysis_counter]->configure(nodesin);
+	this->hvertices->configure(verticesin);
+	this->hmaterial->configure(materialsin);
+	this->hmatpar->configure(materialsin);
+
+	/*Now, go pick up the objects inside the hooks: */
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+	this->vertices = (Vertex**)this->hvertices->deliverp();
+	this->material = (Material*)this->hmaterial->delivers();
+	this->matpar   = (Matpar*)this->hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+	/*get inputs configured too: */
+	this->inputs->Configure(parameters);
+
+}
+/*}}}*/
+/*FUNCTION Tria::DeepEcho{{{*/
+void Tria::DeepEcho(void){
+
+	_printf_("Tria:\n");
+	_printf_("   id: " << id << "\n");
+	if(nodes){
+		nodes[0]->DeepEcho();
+		nodes[1]->DeepEcho();
+		nodes[2]->DeepEcho();
+	}
+	else _printf_("nodes = NULL\n");
+
+	if (material) material->DeepEcho();
+	else _printf_("material = NULL\n");
+
+	if (matpar) matpar->DeepEcho();
+	else _printf_("matpar = NULL\n");
+
+	_printf_("   parameters\n");
+	if (parameters) parameters->DeepEcho();
+	else _printf_("parameters = NULL\n");
+
+	_printf_("   inputs\n");
+	if (inputs) inputs->DeepEcho();
+	else _printf_("inputs=NULL\n");
+
+	if (results) results->DeepEcho();
+	else _printf_("results=NULL\n");
+
+	_printf_("neighboor sids: \n");
+	_printf_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2] << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Tria::DeleteResults {{{*/
+void  Tria::DeleteResults(void){
+
+	/*Delete and reinitialize results*/
+	delete this->results;
+	this->results=new Results();
+
+}
+/*}}}*/
+/*FUNCTION Tria::Delta18oParameterization{{{*/
+void  Tria::Delta18oParameterization(void){
+
+	int        i;
+	IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+	IssmDouble TemperaturesPresentday[NUMVERTICES][12],TemperaturesLgm[NUMVERTICES][12];
+	IssmDouble PrecipitationsPresentday[NUMVERTICES][12];
+	IssmDouble tmp[NUMVERTICES];
+	IssmDouble Delta18oPresent,Delta18oLgm,Delta18oTime;
+	IssmDouble Delta18oSurfacePresent,Delta18oSurfaceLgm,Delta18oSurfaceTime;
+	IssmDouble time,yts,finaltime;
+
+	/*Recover parameters*/
+	this->parameters->FindParam(&time,TimeEnum);
+	this->parameters->FindParam(&yts,ConstantsYtsEnum);
+	this->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+
+	/*Recover present day temperature and precipitation*/
+	Input* input=inputs->GetInput(SurfaceforcingsTemperaturesPresentdayEnum);    _assert_(input);
+	Input* input2=inputs->GetInput(SurfaceforcingsTemperaturesLgmEnum);          _assert_(input2);
+	Input* input3=inputs->GetInput(SurfaceforcingsPrecipitationsPresentdayEnum); _assert_(input3);
+	GaussTria* gauss=new GaussTria();
+	for(int month=0;month<12;month++){
+		for(int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&TemperaturesPresentday[iv][month],gauss,month/12.*yts);
+			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
+			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
+			PrecipitationsPresentday[iv][month]=PrecipitationsPresentday[iv][month]/yts; // converion in m/sec
+		}
+	}
+
+	/*Recover delta18o and Delta18oSurface at present day, lgm and at time t*/
+	this->parameters->FindParam(&Delta18oPresent,SurfaceforcingsDelta18oEnum,finaltime);
+	this->parameters->FindParam(&Delta18oLgm,SurfaceforcingsDelta18oEnum,(finaltime-(21000*yts)));
+	this->parameters->FindParam(&Delta18oTime,SurfaceforcingsDelta18oEnum,time);
+	this->parameters->FindParam(&Delta18oSurfacePresent,SurfaceforcingsDelta18oSurfaceEnum,finaltime);
+	this->parameters->FindParam(&Delta18oSurfaceLgm,SurfaceforcingsDelta18oSurfaceEnum,(finaltime-(21000*yts)));
+	this->parameters->FindParam(&Delta18oSurfaceTime,SurfaceforcingsDelta18oSurfaceEnum,time);
+
+	/*Compute the temperature and precipitation*/
+	for(int iv=0;iv<NUMVERTICES;iv++){
+		ComputeDelta18oTemperaturePrecipitation(Delta18oSurfacePresent, Delta18oSurfaceLgm, Delta18oSurfaceTime, 
+					Delta18oPresent, Delta18oLgm, Delta18oTime,
+					&PrecipitationsPresentday[iv][0], 
+					&TemperaturesLgm[iv][0], &TemperaturesPresentday[iv][0], 
+					&monthlytemperatures[iv][0], &monthlyprec[iv][0]);
+	}
+
+	/*Update inputs*/ 
+	TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
+	TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
+	for (int imonth=0;imonth<12;imonth++) {
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
+		TriaInput* newmonthinput1 = new TriaInput(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0],P1Enum);
+		NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);
+
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlyprec[i][imonth];
+		TriaInput* newmonthinput2 = new TriaInput(SurfaceforcingsPrecipitationEnum,&tmp[0],P1Enum);
+		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
+	}
+
+	this->inputs->AddInput(NewTemperatureInput);
+	this->inputs->AddInput(NewPrecipitationInput);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::Echo{{{*/
+void Tria::Echo(void){
+	_printf_("Tria:\n");
+	_printf_("   id: " << id << "\n");
+	if(nodes){
+		nodes[0]->Echo();
+		nodes[1]->Echo();
+		nodes[2]->Echo();
+	}
+	else _printf_("nodes = NULL\n");
+
+	if (material) material->Echo();
+	else _printf_("material = NULL\n");
+
+	if (matpar) matpar->Echo();
+	else _printf_("matpar = NULL\n");
+
+	_printf_("   parameters\n");
+	if (parameters) parameters->Echo();
+	else _printf_("parameters = NULL\n");
+
+	_printf_("   inputs\n");
+	if (inputs) inputs->Echo();
+	else _printf_("inputs=NULL\n");
+
+	if (results) results->Echo();
+	else _printf_("results=NULL\n");
+
+	_printf_("neighboor sids: \n");
+	_printf_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2] << "\n");
+}
+/*}}}*/
+/*FUNCTION Tria::ObjectEnum{{{*/
+int Tria::ObjectEnum(void){
+
+	return TriaEnum;
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetArea {{{*/
+IssmDouble Tria::GetArea(void){
+
+	IssmDouble area=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble x1,y1,x2,y2,x3,y3;
+
+	/*Get xyz list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	x1=xyz_list[0][0]; y1=xyz_list[0][1];
+	x2=xyz_list[1][0]; y2=xyz_list[1][1];
+	x3=xyz_list[2][0]; y3=xyz_list[2][1];
+
+	_assert_(x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1>0);
+	return (x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1)/2;
+}
+/*}}}*/
+/*FUNCTION Tria::GetDofList {{{*/
+void  Tria::GetDofList(int** pdoflist, int approximation_enum,int setenum){
+
+	int i,j;
+	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++){
+		nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
+/*FUNCTION Tria::GetElementType {{{*/
+int Tria::GetElementType(){
+
+	/*return TriaRef field*/
+	return this->element_type;
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetHorizontalNeighboorSids {{{*/
+int* Tria::GetHorizontalNeighboorSids(){
+
+	/*return TriaRef field*/
+	return &this->horizontalneighborsids[0];
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetGroundedPortion{{{*/
+IssmDouble Tria::GetGroundedPortion(IssmDouble* xyz_list){
+	/*Computeportion of the element that is grounded*/ 
+
+	bool               mainlyfloating = true;
+	const IssmPDouble  epsilon= 1.e-15;
+	IssmDouble         phi,s1,s2,area_init,area_grounded;
+	IssmDouble         gl[3];
+	IssmDouble         xyz_bis[3][3];
+
+	/*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
+		phi=1;
+	}
+	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
+		phi=0;
+	}
+	else{
+		/*Figure out if two nodes are floating or grounded*/
+		if(gl[0]*gl[1]*gl[2]>0) mainlyfloating=false;
+
+		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+			/*Coordinates of point 2: same as initial point 2*/
+			xyz_bis[2][0]=*(xyz_list+3*2+0);
+			xyz_bis[2][1]=*(xyz_list+3*2+1);
+			xyz_bis[2][2]=*(xyz_list+3*2+2);
+
+			/*Portion of the segments*/
+			s1=gl[2]/(gl[2]-gl[1]);
+			s2=gl[2]/(gl[2]-gl[0]);
+
+			/*New point 1*/
+			xyz_bis[1][0]=*(xyz_list+3*2+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*2+0));
+			xyz_bis[1][1]=*(xyz_list+3*2+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*2+1));
+			xyz_bis[1][2]=*(xyz_list+3*2+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*2+2));
+
+			/*New point 0*/
+			xyz_bis[0][0]=*(xyz_list+3*2+0)+s2*(*(xyz_list+3*0+0)-*(xyz_list+3*2+0));
+			xyz_bis[0][1]=*(xyz_list+3*2+1)+s2*(*(xyz_list+3*0+1)-*(xyz_list+3*2+1));
+			xyz_bis[0][2]=*(xyz_list+3*2+2)+s2*(*(xyz_list+3*0+2)-*(xyz_list+3*2+2));
+		}
+		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+			/*Coordinates of point 0: same as initial point 2*/
+			xyz_bis[0][0]=*(xyz_list+3*0+0);
+			xyz_bis[0][1]=*(xyz_list+3*0+1);
+			xyz_bis[0][2]=*(xyz_list+3*0+2);
+
+			/*Portion of the segments*/
+			s1=gl[0]/(gl[0]-gl[1]);
+			s2=gl[0]/(gl[0]-gl[2]);
+
+			/*New point 1*/
+			xyz_bis[1][0]=*(xyz_list+3*0+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*0+0));
+			xyz_bis[1][1]=*(xyz_list+3*0+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*0+1));
+			xyz_bis[1][2]=*(xyz_list+3*0+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*0+2));
+
+			/*New point 2*/
+			xyz_bis[2][0]=*(xyz_list+3*0+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*0+0));
+			xyz_bis[2][1]=*(xyz_list+3*0+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*0+1));
+			xyz_bis[2][2]=*(xyz_list+3*0+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*0+2));
+		}
+		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+			/*Coordinates of point 1: same as initial point 2*/
+			xyz_bis[1][0]=*(xyz_list+3*1+0);
+			xyz_bis[1][1]=*(xyz_list+3*1+1);
+			xyz_bis[1][2]=*(xyz_list+3*1+2);
+
+			/*Portion of the segments*/
+			s1=gl[1]/(gl[1]-gl[0]);
+			s2=gl[1]/(gl[1]-gl[2]);
+
+			/*New point 0*/
+			xyz_bis[0][0]=*(xyz_list+3*1+0)+s1*(*(xyz_list+3*0+0)-*(xyz_list+3*1+0));
+			xyz_bis[0][1]=*(xyz_list+3*1+1)+s1*(*(xyz_list+3*0+1)-*(xyz_list+3*1+1));
+			xyz_bis[0][2]=*(xyz_list+3*1+2)+s1*(*(xyz_list+3*0+2)-*(xyz_list+3*1+2));
+
+			/*New point 2*/
+			xyz_bis[2][0]=*(xyz_list+3*1+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*1+0));
+			xyz_bis[2][1]=*(xyz_list+3*1+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*1+1));
+			xyz_bis[2][2]=*(xyz_list+3*1+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*1+2));
+		}
+
+		/*Compute fraction of grounded element*/
+		GetJacobianDeterminant(&area_init, xyz_list,NULL);
+		GetJacobianDeterminant(&area_grounded, &xyz_bis[0][0],NULL);
+		if(mainlyfloating==true) area_grounded=area_init-area_grounded;
+		phi=area_grounded/area_init;
+	}
+
+	if(phi>1 || phi<0) _error_("Error. Problem with portion of grounded element: value should be between 0 and 1");
+
+	return phi;
+}
+/*}}}*/
+/*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[3];
+	IssmDouble         f1,f2;
+
+	/*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;
+}
+/*}}}*/
+/*FUNCTION Tria::GetNodeIndex {{{*/
+int Tria::GetNodeIndex(Node* node){
+
+	_assert_(nodes);
+	for(int i=0;i<NUMVERTICES;i++){
+		if(node==nodes[i])
+		 return i;
+	}
+	_error_("Node provided not found among element nodes");
+}
+/*}}}*/
+/*FUNCTION Tria::GetNodesSidList{{{*/
+void Tria::GetNodesSidList(int* sidlist){
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++){
+		sidlist[i]=nodes[i]->Sid();
+	}
+}
+/*}}}*/
+/*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");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype) {{{*/
+void Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){
+
+	/*Recover input*/
+	Input* input=inputs->GetInput(enumtype);
+	if (!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	GaussTria* gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue) {{{*/
+void Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){
+
+	Input     *input = inputs->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		GaussTria* gauss=new GaussTria();
+		for (int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+		delete gauss;
+	}
+	else{
+		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue,int index) TO BE REMOVED{{{*/
+void Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue,int index){
+
+	Input     *input = inputs->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		GaussTria* gauss=new GaussTria();
+		for (int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&pvalue[iv],gauss,index);
+		}
+		delete gauss;
+	}
+	else{
+		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue) {{{*/
+void Tria::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){
+		GaussTria* gauss=new GaussTria();
+		for (int iv=0;iv<this->NumberofNodes();iv++){
+			gauss->GaussNode(numnodes,iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+		delete gauss;
+	}
+	else{
+		for (int iv=0;iv<numnodes;iv++) pvalue[iv]=defaultvalue;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputListOnNodes(IssmDouble* pvalue,int enumtype) {{{*/
+void Tria::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: */
+	GaussTria* gauss=new GaussTria();
+	for (int iv=0;iv<this->NumberofNodes();iv++){
+		gauss->GaussNode(numnodes,iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype) {{{*/
+void Tria::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){
+
+	Input* input=inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussTria* gauss=new GaussTria();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GetVertexPidList {{{*/
+void  Tria::GetVertexPidList(int* doflist){
+
+	for(int i=0;i<3;i++) doflist[i]=vertices[i]->Pid();
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetVertexSidList {{{*/
+void  Tria::GetVertexSidList(int* sidlist){
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=vertices[i]->Sid();
+}
+/*}}}*/
+/*FUNCTION Tria::GetConnectivityList {{{*/
+void  Tria::GetConnectivityList(int* connectivity){
+	for(int i=0;i<NUMVERTICES;i++) connectivity[i]=nodes[i]->GetConnectivity();
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputs{{{*/
+void  Tria::GetSolutionFromInputs(Vector<IssmDouble>* solution){
+
+	/*retrive parameters: */
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*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);
+		break;
+	case DiagnosticHutterAnalysisEnum:
+		GetSolutionFromInputsDiagnosticHutter(solution);
+		break;
+	#endif
+	#ifdef _HAVE_HYDROLOGY_
+	case HydrologyShreveAnalysisEnum:
+		GetSolutionFromInputsOneDof(solution,WatercolumnEnum);
+		break;
+	case HydrologyDCInefficientAnalysisEnum:
+		GetSolutionFromInputsOneDof(solution,SedimentHeadEnum);
+		break;
+	case HydrologyDCEfficientAnalysisEnum:
+		GetSolutionFromInputsOneDof(solution,EplHeadEnum);
+		break;
+	#endif
+	default:
+		_error_("analysis: " << EnumToStringx(analysis_type) << " not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetStrainRate2d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussTria* gauss, Input* vx_input, Input* vy_input){{{*/
+void Tria::GetStrainRate2d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussTria* gauss, Input* vx_input, Input* vy_input){
+	/*Compute the 2d Strain Rate (3 components):
+	 * epsilon=[exx eyy exy] */
+
+	int i;
+	IssmDouble epsilonvx[3];
+	IssmDouble epsilonvy[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetVxStrainRate2d(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate2d(epsilonvy,xyz_list,gauss);
+
+	/*Sum all contributions*/
+	for(i=0;i<3;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i];
+}
+/*}}}*/
+/*FUNCTION Tria::GetVectorFromInputs{{{*/
+void  Tria::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
+
+	int vertexpidlist[NUMVERTICES];
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(input_enum)) return;
+
+	/*Prepare index list*/
+	this->GetVertexPidList(&vertexpidlist[0]);
+
+	/*Get input (either in element or material)*/
+	Input* input=inputs->GetInput(input_enum);
+	if(!input) _error_("Input " << EnumToStringx(input_enum) << " not found in element");
+
+	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+	input->GetVectorFromInputs(vector,&vertexpidlist[0]);
+}
+/*}}}*/
+/*FUNCTION Tria::GetVectorFromResults{{{*/
+void  Tria::GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int enum_in,int interp){
+
+	/*Get result*/
+	ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(offset);
+	if(elementresult->InstanceEnum()!=enum_in){
+		_error_("Results of offset "<<offset<<" is "<<EnumToStringx(elementresult->InstanceEnum())<<" when "<<EnumToStringx(enum_in)<<" was expected");
+	}
+	if(interp==P1Enum){
+		int vertexpidlist[NUMVERTICES];
+		int connectivity[NUMVERTICES];
+		this->GetVertexSidList(&vertexpidlist[0]);
+		this->GetConnectivityList(&connectivity[0]);
+		elementresult->GetVectorFromResults(vector,&vertexpidlist[0],&connectivity[0],NUMVERTICES);
+	}
+	else if(interp==P0Enum){
+		elementresult->GetElementVectorFromResults(vector,sid);
+	}
+	else{
+		_printf_("Interpolation " << EnumToStringx(interp) << " not supported\n");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::Id {{{*/
+int    Tria::Id(){
+
+	return id;
+
+}
+/*}}}*/
+/*FUNCTION Tria::Sid {{{*/
+int    Tria::Sid(){
+
+	return sid;
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputArtificialNoise{{{*/
+void  Tria::InputArtificialNoise(int enum_type,IssmDouble min,IssmDouble max){
+
+	Input* input=NULL;
+
+	/*Make a copy of the original input: */
+	input=(Input*)this->inputs->GetInput(enum_type);
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+
+	/*ArtificialNoise: */
+	input->ArtificialNoise(min,max);
+}
+/*}}}*/
+/*FUNCTION Tria::InputDepthAverageAtBase {{{*/
+void  Tria::InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum){
+
+	/*New input*/
+	Input* oldinput=NULL;
+	Input* newinput=NULL;
+
+	/*copy input of enum_type*/
+	if (object_enum==MeshElementsEnum)
+	 oldinput=(Input*)this->inputs->GetInput(enum_type);
+	else if (object_enum==MaterialsEnum)
+	 oldinput=(Input*)this->material->inputs->GetInput(enum_type);
+	else
+	 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
+	if(!oldinput)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+	newinput=(Input*)oldinput->copy();
+
+	/*Assign new name (average)*/
+	newinput->ChangeEnum(average_enum_type);
+
+	/*Add new input to current element*/
+	if (object_enum==MeshElementsEnum)
+	 this->inputs->AddInput((Input*)newinput);
+	else if (object_enum==MaterialsEnum)
+	 this->material->inputs->AddInput((Input*)newinput);
+	else
+	 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
+}
+/*}}}*/
+/*FUNCTION Tria::InputDuplicate{{{*/
+void  Tria::InputDuplicate(int original_enum,int new_enum){
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputScale{{{*/
+void  Tria::InputScale(int enum_type,IssmDouble scale_factor){
+
+	Input* input=NULL;
+
+	/*Make a copy of the original input: */
+	input=(Input*)this->inputs->GetInput(enum_type);
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+
+	/*Scale: */
+	input->Scale(scale_factor);
+}
+/*}}}*/
+/*FUNCTION Tria::InputToResult{{{*/
+void  Tria::InputToResult(int enum_type,int step,IssmDouble time){
+
+	Input *input = NULL;	
+
+	/*Go through all the input objects, and find the one corresponding to enum_type, if it exists: */
+	if (enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum)
+	 input=this->material->inputs->GetInput(enum_type);
+	else
+	 input=this->inputs->GetInput(enum_type);
+	//if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found in tria->inputs");
+	if(!input)return;
+
+	/*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));
+
+	#ifdef _HAVE_CONTROL_
+	if(input->ObjectEnum()==ControlInputEnum){
+		if(((ControlInput*)input)->gradient!=NULL) this->results->AddObject((Object*)((ControlInput*)input)->SpawnGradient(step,time));
+	}
+	#endif
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromConstant(int value, int name);{{{*/
+void  Tria::InputUpdateFromConstant(int constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new IntInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromConstant(IssmDouble value, int name);{{{*/
+void  Tria::InputUpdateFromConstant(IssmDouble constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new DoubleInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromConstant(bool value, int name);{{{*/
+void  Tria::InputUpdateFromConstant(bool constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new BoolInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromIoModel{{{*/
+void Tria::InputUpdateFromIoModel(int index, IoModel* iomodel){ //i is the element index
+
+	/*Intermediaries*/
+	int        i,j;
+	int        tria_vertex_ids[3];
+	IssmDouble nodeinputs[3];
+	IssmDouble cmmininputs[3];
+	IssmDouble cmmaxinputs[3];
+	bool       control_analysis   = false;
+	int        num_control_type;
+	IssmDouble yts;
+	int        num_cm_responses;
+
+	/*Get parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum); 
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+	if(control_analysis) iomodel->Constant(&num_cm_responses,InversionNumCostFunctionsEnum);
+
+	/*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
+	}
+
+	/*Control Inputs*/
+	#ifdef _HAVE_CONTROL_
+	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+		for(i=0;i<num_control_type;i++){
+			switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
+				case BalancethicknessThickeningRateEnum:
+					if (iomodel->Data(BalancethicknessThickeningRateEnum)){
+						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(BalancethicknessThickeningRateEnum)[tria_vertex_ids[j]-1];
+						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case VxEnum:
+					if (iomodel->Data(VxEnum)){
+						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(VxEnum)[tria_vertex_ids[j]-1];
+						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(VxEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case VyEnum:
+					if (iomodel->Data(VyEnum)){
+						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(VyEnum)[tria_vertex_ids[j]-1];
+						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(VyEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case ThicknessEnum:
+					if (iomodel->Data(ThicknessEnum)){
+						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(ThicknessEnum)[tria_vertex_ids[j]-1];
+						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(ThicknessEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case FrictionCoefficientEnum:
+					if (iomodel->Data(FrictionCoefficientEnum)){
+						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(FrictionCoefficientEnum)[tria_vertex_ids[j]-1];
+						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case MaterialsRheologyBbarEnum:
+				case MaterialsRheologyZbarEnum:
+					/*Material will take care of it*/ break;
+				default:
+					_error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
+			}
+		}
+	}
+	#endif
+
+	/*DatasetInputs*/
+	if (control_analysis && iomodel->Data(InversionCostFunctionsCoefficientsEnum)){
+
+		/*Create inputs and add to DataSetInput*/
+		DatasetInput* datasetinput=new DatasetInput(InversionCostFunctionsCoefficientsEnum);
+		for(i=0;i<num_cm_responses;i++){
+			for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(tria_vertex_ids[j]-1)*num_cm_responses+i];
+			datasetinput->inputs->AddObject(new TriaInput(InversionCostFunctionsCoefficientsEnum,nodeinputs,P1Enum));
+		}
+
+		/*Add datasetinput to element inputs*/
+		this->inputs->AddInput(datasetinput);
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolution {{{*/
+void  Tria::InputUpdateFromSolution(IssmDouble* solution){
+
+	/*retrive parameters: */
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*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);
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			InputUpdateFromSolutionDiagnosticHoriz(solution);
+			break;
+		#endif
+		#ifdef _HAVE_CONTROL_
+		case AdjointHorizAnalysisEnum:
+			InputUpdateFromSolutionAdjointHoriz(solution);
+			break;
+		case AdjointBalancethicknessAnalysisEnum:
+			InputUpdateFromSolutionAdjointBalancethickness(solution);
+			break;
+		#endif
+		#ifdef _HAVE_HYDROLOGY_ 
+		case HydrologyShreveAnalysisEnum:
+			InputUpdateFromSolutionHydrologyShreve(solution);
+			break;
+		case HydrologyDCInefficientAnalysisEnum:
+			InputUpdateFromSolutionHydrologyDCInefficient(solution);
+			break;
+		case HydrologyDCEfficientAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,EplHeadEnum);
+			break;
+		#endif
+	 	#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,ThicknessEnum);
+			break;
+		#endif
+		case BedSlopeXAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,BedSlopeXEnum);
+			break;
+		case BedSlopeYAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,BedSlopeYEnum);
+			break;
+		case SurfaceSlopeXAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,SurfaceSlopeXEnum);
+			break;
+		case SurfaceSlopeYAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,SurfaceSlopeYEnum);
+			break;
+		case PrognosticAnalysisEnum:
+			InputUpdateFromSolutionPrognostic(solution);
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionOneDof{{{*/
+void  Tria::InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type){
+
+	const int  numdof         = NDOF1*NUMVERTICES;
+	int*       doflist        = NULL;
+	IssmDouble values[numdof];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaInput(enum_type,values,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionPrognostic{{{*/
+void  Tria::InputUpdateFromSolutionPrognostic(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: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	this->parameters->FindParam(&minthickness,PrognosticMinThicknessEnum);
+	for(i=0;i<numdof;i++){
+		newthickness[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(newthickness[i])) _error_("NaN found in solution vector");
+		/*Constrain thickness to be at least 1m*/
+		if(newthickness[i]<minthickness) newthickness[i]=minthickness;
+	}
+
+	/*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);
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	for(i=0;i<numdof;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
+		}
+		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);
+			}
+			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
+			}
+			else _error_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
+		}
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaInput(ThicknessEnum,newthickness,P1Enum));
+	this->inputs->AddInput(new TriaInput(SurfaceEnum,newsurface,P1Enum));
+	this->inputs->AddInput(new TriaInput(BedEnum,newbed,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVector(IssmDouble* vector, int name, int type);{{{*/
+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;
+
+	switch(type){
+	case VertexPIdEnum: 
+		for (int i=0;i<NUMVERTICES;i++){
+			values[i]=vector[this->vertices[i]->Pid()];
+		}
+		/*update input*/
+		if (name==MaterialsRheologyBbarEnum || name==MaterialsRheologyBEnum || name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
+			material->inputs->AddInput(new TriaInput(name,values,P1Enum));
+		}
+		else{
+			this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+		}
+		return; 
+
+	case VertexSIdEnum: 
+		for (int i=0;i<NUMVERTICES;i++){
+			values[i]=vector[this->vertices[i]->Sid()];
+		}
+		/*update input*/
+		if (name==MaterialsRheologyBbarEnum || name==MaterialsRheologyBEnum || name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
+			material->inputs->AddInput(new TriaInput(name,values,P1Enum));
+		}
+		else{
+			this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+		}
+		return; 
+
+	case NodesEnum:
+		/*Get dof list: */
+		GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+		/*Use the dof list to index into the vector: */
+		for(int i=0;i<numdof;i++){
+			values[i]=vector[doflist[i]];
+			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+		}
+		/*Add input to the element: */
+		this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+
+		/*Free ressources:*/
+		xDelete<int>(doflist);
+		return;
+
+	case NodeSIdEnum:
+		for(int i=0;i<NUMVERTICES;i++){
+			values[i]=vector[nodes[i]->Sid()];
+			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+		}
+		/*Add input to the element: */
+		this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+
+		/*Free ressources:*/
+		xDelete<int>(doflist);
+		return;
+
+	default:
+		_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+/*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!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputCreate(IssmDouble scalar,int enum,int code);{{{*/
+void Tria::InputCreate(IssmDouble scalar,int name,int code){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	if ((code==5) || (code==1)){ //boolean
+		this->inputs->AddInput(new BoolInput(name,reCast<bool>(scalar)));
+	}
+	else if ((code==6) || (code==2)){ //integer
+		this->inputs->AddInput(new IntInput(name,reCast<int>(scalar)));
+	}
+	else if ((code==7) || (code==3)){ //IssmDouble
+		this->inputs->AddInput(new DoubleInput(name,reCast<int>(scalar)));
+	}
+	else _error_("could not recognize nature of vector from code " << code);
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputCreate(IssmDouble* vector,int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){{{*/
+void Tria::InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){//index into elements
+
+	/*Intermediaries*/
+	int    i,j,t;
+	int    tria_vertex_ids[3];
+	int    row;
+	IssmDouble nodeinputs[3];
+	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: */
+	if(vector_type==1){ //nodal vector
+
+		/*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
+		}
+
+		/*Are we in transient or static? */
+		if(M==numberofvertices){
+
+			/*create input values: */
+			for(i=0;i<3;i++)nodeinputs[i]=(IssmDouble)vector[tria_vertex_ids[i]-1];
+
+			/*create static input: */
+			this->inputs->AddInput(new TriaInput(vector_enum,nodeinputs,P1Enum));
+		}
+		else if(M==numberofvertices+1){
+			/*create transient input: */
+			for(t=0;t<N;t++){ //N is the number of times
+
+				/*create input values: */
+				for(i=0;i<3;i++){
+					row=tria_vertex_ids[i]-1;
+					nodeinputs[i]=(IssmDouble)vector[N*row+t];
+				}
+
+				/*time? :*/
+				time=(IssmDouble)vector[(M-1)*N+t]*yts;
+
+				if(t==0) transientinput=new TransientInput(vector_enum);
+				transientinput->AddTimeInput(new TriaInput(vector_enum,nodeinputs,P1Enum),time);
+			}
+			this->inputs->AddInput(transientinput);
+		}
+		else _error_("nodal vector is either numberofnodes or numberofnodes+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){
+
+			/*static mode: create an input out of the element value: */
+
+			if (code==5){ //boolean
+				this->inputs->AddInput(new BoolInput(vector_enum,reCast<bool>(vector[index])));
+			}
+			else if (code==6){ //integer
+				this->inputs->AddInput(new IntInput(vector_enum,reCast<int>(vector[index])));
+			}
+			else if (code==7){ //IssmDouble
+				this->inputs->AddInput(new DoubleInput(vector_enum,vector[index]));
+			}
+			else _error_("could not recognize nature of vector from code " << code);
+		}
+		else {
+			_error_("transient element inputs not supported yet!");
+		}
+	}
+	else{
+		_error_("Cannot add input for vector type " << vector_type << " (not supported)");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::IsInput{{{*/
+bool Tria::IsInput(int name){
+	if (
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==BathymetryEnum ||
+				name==BedEnum ||
+				name==GLlevelsetEnum ||
+				name==SurfaceSlopeXEnum ||
+				name==SurfaceSlopeYEnum ||
+				name==BasalforcingsMeltingRateEnum ||
+				name==WatercolumnEnum || 
+				name==SurfaceforcingsMassBalanceEnum ||
+				name==SurfaceAreaEnum||
+				name==VxEnum ||
+				name==VyEnum ||
+				name==InversionVxObsEnum ||
+				name==InversionVyObsEnum ||
+				name==FrictionCoefficientEnum ||
+				name==MaterialsRheologyBbarEnum ||
+				name==MaterialsRheologyZbarEnum ||
+				name==GradientEnum ||
+				name==OldGradientEnum ||
+				name==ConvergedEnum ||
+				name==SedimentHeadOldEnum ||
+				name==SedimentHeadEnum ||
+				name==EplHeadOldEnum ||
+				name==EplHeadEnum ||
+				name==HydrologydcMaskEplactiveEnum ||
+				name==WaterTransferEnum ||
+				name==QmuVxEnum ||
+				name==QmuVyEnum ||
+				name==QmuPressureEnum ||
+				name==QmuBedEnum ||
+				name==QmuThicknessEnum ||
+				name==QmuSurfaceEnum ||
+				name==QmuTemperatureEnum ||
+				name==QmuMeltingEnum || 
+				name==GiaWEnum || 
+				name==GiadWdtEnum
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
+/*FUNCTION Tria::IsOnBed {{{*/
+bool Tria::IsOnBed(){
+
+	bool onbed;
+	inputs->GetInputValue(&onbed,MeshElementonbedEnum);
+	return onbed;
+}
+/*}}}*/
+/*FUNCTION Tria::IsFloating {{{*/
+bool   Tria::IsFloating(){
+
+	bool shelf;
+	inputs->GetInputValue(&shelf,MaskElementonfloatingiceEnum);
+	return shelf;
+}
+/*}}}*/
+/*FUNCTION Tria::IsNodeOnShelf {{{*/
+bool   Tria::IsNodeOnShelf(){
+
+	int  i;
+	bool shelf=false;
+
+	for(i=0;i<3;i++){
+		if (nodes[i]->IsFloating()){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
+}
+/*}}}*/
+/*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::ListResultsInfo{{{*/
+void Tria::ListResultsInfo(int** in_resultsenums,int** in_resultssizes,IssmDouble** in_resultstimes,int** in_resultssteps,int* in_num_results){
+
+	/*Intermediaries*/
+	int     i;
+	int     numberofresults = 0;
+	int     *resultsenums   = NULL;
+	int     *resultssizes   = NULL;
+	IssmDouble  *resultstimes   = NULL;
+	int     *resultssteps   = NULL;
+
+	/*Checks*/
+	_assert_(in_num_results);
+
+	/*Count number of results*/
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		numberofresults++;
+	}
+
+	if(numberofresults){
+
+		/*Allocate output*/
+		resultsenums=xNew<int>(numberofresults);
+		resultssizes=xNew<int>(numberofresults);
+		resultstimes=xNew<IssmDouble>(numberofresults);
+		resultssteps=xNew<int>(numberofresults);
+
+		/*populate enums*/
+		for(i=0;i<this->results->Size();i++){
+			ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+			resultsenums[i]=elementresult->InstanceEnum();
+			resultstimes[i]=elementresult->GetTime();
+			resultssteps[i]=elementresult->GetStep();
+			if(elementresult->ObjectEnum()==TriaP1ElementResultEnum){
+				resultssizes[i]=P1Enum;
+			}
+			else{
+				resultssizes[i]=P0Enum;
+			}
+		}
+	}
+
+	/*Assign output pointers:*/
+	*in_num_results=numberofresults;
+	*in_resultsenums=resultsenums;
+	*in_resultssizes=resultssizes;
+	*in_resultstimes=resultstimes;
+	*in_resultssteps=resultssteps;
+
+}/*}}}*/
+/*FUNCTION Tria::NodalValue {{{*/
+int    Tria::NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){
+
+	int         found = 0;
+	IssmDouble  value;
+	Input      *data  = NULL;
+	GaussTria  *gauss = NULL;
+
+	/*First, serarch the input: */
+	data=inputs->GetInput(natureofdataenum); 
+
+	/*figure out if we have the vertex id: */
+	found=0;
+	for(int i=0;i<NUMVERTICES;i++){
+		if(index==vertices[i]->Id()){
+			/*Do we have natureofdataenum in our inputs? :*/
+			if(data){
+				/*ok, we are good. retrieve value of input at vertex :*/
+				gauss=new GaussTria(); gauss->GaussVertex(i);
+				data->GetInputValue(&value,gauss);
+				found=1;
+				break;
+			}
+		}
+	}
+
+	/*clean-up*/
+	delete gauss;
+
+	if(found)*pvalue=value;
+	return found;
+}
+/*}}}*/
+/*FUNCTION Tria::PatchFill{{{*/
+void  Tria::PatchFill(int* prow, Patch* patch){
+
+	int i,row;
+	int vertices_ids[3];
+
+	/*recover pointer: */
+	row=*prow;
+
+	for(i=0;i<3;i++) vertices_ids[i]=vertices[i]->Id(); //vertices id start at column 3 of the patch.
+
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+
+		/*For this result,fill the information in the Patch object (element id + vertices ids), and then hand 
+		 *it to the result object, to fill the rest: */
+		patch->fillelementinfo(row,this->sid+1,vertices_ids,3);
+		elementresult->PatchFill(row,patch);
+
+		/*increment rower: */
+		row++;
+	}
+
+	/*Assign output pointers:*/
+	*prow=row;
+}
+/*}}}*/
+/*FUNCTION Tria::PatchSize{{{*/
+void  Tria::PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes){
+
+	int     i;
+	int     numrows       = 0;
+	int     numnodes      = 0;
+	int     temp_numnodes = 0;
+
+	/*Go through all the results objects, and update the counters: */
+	for (i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		/*first, we have one more result: */
+		numrows++;
+		/*now, how many vertices and how many nodal values for this result? :*/
+		temp_numnodes=elementresult->NumberOfNodalValues(); //ask result object.
+		if(temp_numnodes>numnodes)numnodes=temp_numnodes;
+	}
+
+	/*Assign output pointers:*/
+	*pnumrows=numrows;
+	*pnumvertices=NUMVERTICES;
+	*pnumnodes=numnodes;
+}
+/*}}}*/
+/*FUNCTION Tria::PositiveDegreeDay{{{*/
+void  Tria::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){
+
+   IssmDouble agd[NUMVERTICES];             // surface mass balance
+   IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+   IssmDouble h[NUMVERTICES],s[NUMVERTICES];
+   IssmDouble rho_water,rho_ice,desfac,s0p;
+
+   /*Recover monthly temperatures and precipitation*/
+   Input*     input=inputs->GetInput(SurfaceforcingsMonthlytemperaturesEnum); _assert_(input);
+   Input*     input2=inputs->GetInput(SurfaceforcingsPrecipitationEnum); _assert_(input2);
+   GaussTria* gauss=new GaussTria();
+   IssmDouble time,yts;
+   this->parameters->FindParam(&time,TimeEnum);
+   this->parameters->FindParam(&yts,ConstantsYtsEnum);
+   for(int month=0;month<12;month++) {
+     for(int iv=0;iv<NUMVERTICES;iv++) {
+       gauss->GaussVertex(iv);
+       input->GetInputValue(&monthlytemperatures[iv][month],gauss,time+month/12.*yts);
+       monthlytemperatures[iv][month]=monthlytemperatures[iv][month]-273.15; // conversion from Kelvin to celcius
+       input2->GetInputValue(&monthlyprec[iv][month],gauss,time+month/12.*yts);
+       monthlyprec[iv][month]=monthlyprec[iv][month]*yts; // convertion in m/y
+     }
+   }
+
+  /*Recover info at the vertices: */
+  GetInputListOnVertices(&h[0],ThicknessEnum);
+  GetInputListOnVertices(&s[0],SurfaceEnum);
+
+  /*Get material parameters :*/
+  rho_ice=matpar->GetRhoIce();
+  rho_water=matpar->GetRhoFreshwater();
+
+  /*Get desertification effect parameters*/
+  desfac=matpar->GetDesFac();
+  s0p=matpar->GetS0p();
+
+   /*measure the surface mass balance*/
+   for (int iv = 0; iv<NUMVERTICES; iv++){
+     agd[iv]=PddSurfaceMassBlance(&monthlytemperatures[iv][0], &monthlyprec[iv][0], pdds, pds, signorm, yts, h[iv], s[iv], rho_ice, rho_water, desfac, s0p);
+   }
+
+   /*Update inputs*/    
+   this->inputs->AddInput(new TriaInput(SurfaceforcingsMassBalanceEnum,&agd[0],P1Enum));
+   // this->inputs->AddInput(new TriaVertexInput(ThermalSpcTemperatureEnum,&Tsurf[0]));
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::RequestedOutput{{{*/
+void Tria::RequestedOutput(int output_enum,int step,IssmDouble time){
+
+	if(IsInput(output_enum)){
+		/*just transfer this input to results, and we are done: */
+		InputToResult(output_enum,step,time);
+	}
+	else{
+		/*this input does not exist, compute it, and then transfer to results: */
+		switch(output_enum){
+			case StressTensorEnum: 
+				this->ComputeStressTensor();
+				InputToResult(StressTensorxxEnum,step,time);
+				InputToResult(StressTensorxyEnum,step,time);
+				InputToResult(StressTensorxzEnum,step,time);
+				InputToResult(StressTensoryyEnum,step,time);
+				InputToResult(StressTensoryzEnum,step,time);
+				InputToResult(StressTensorzzEnum,step,time);
+				break;
+
+			default:
+				/*do nothing, no need to derail the computation because one of the outputs requested cannot be found: */
+				break;
+		}
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::SetClone {{{*/
+void  Tria::SetClone(int* minranks){
+
+	_error_("not implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::SmbGradients{{{*/
+void Tria::SmbGradients(void){
+
+	int i;
+
+	// input
+   IssmDouble h[NUMVERTICES];					// ice thickness (m)		
+	IssmDouble s[NUMVERTICES];					// surface elevation (m)
+	IssmDouble b_pos[NUMVERTICES];				// Hs-SMB relation parameter
+	IssmDouble b_neg[NUMVERTICES];				// Hs-SMB relation paremeter
+	IssmDouble Href[NUMVERTICES];					// reference elevation from which deviations are used to calculate the SMB adjustment
+	IssmDouble Smbref[NUMVERTICES];				// reference SMB to which deviations are added
+   IssmDouble rho_water;                   // density of fresh water
+	IssmDouble rho_ice;                     // density of ice
+
+	// output
+	IssmDouble smb[NUMVERTICES];					// surface mass balance (m/yr ice)
+
+	/*Recover SmbGradients*/
+	GetInputListOnVertices(&Href[0],SurfaceforcingsHrefEnum);
+	GetInputListOnVertices(&Smbref[0],SurfaceforcingsSmbrefEnum);
+	GetInputListOnVertices(&b_pos[0],SurfaceforcingsBPosEnum);
+	GetInputListOnVertices(&b_neg[0],SurfaceforcingsBNegEnum);
+
+   /*Recover surface elevatio at vertices: */
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&s[0],SurfaceEnum);
+
+   /*Get material parameters :*/
+   rho_ice=matpar->GetRhoIce();
+   rho_water=matpar->GetRhoFreshwater();
+
+   // loop over all vertices
+   for(i=0;i<NUMVERTICES;i++){
+     if(Smbref[i]>0){
+		  smb[i]=Smbref[i]+b_pos[i]*(s[i]-Href[i]);
+	  }
+	  else{
+		  smb[i]=Smbref[i]+b_neg[i]*(s[i]-Href[i]);
+	  }
+	  smb[i]=smb[i]/rho_ice;      // SMB in m/y ice		
+		}  //end of the loop over the vertices
+	  /*Update inputs*/
+	  this->inputs->AddInput(new TriaInput(SurfaceforcingsMassBalanceEnum,&smb[0],P1Enum));
+}
+/*}}}*/
+/*FUNCTION Tria::SetCurrentConfiguration {{{*/
+void  Tria::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){
+
+	/*go into parameters and get the analysis_counter: */
+	int analysis_counter;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Pick up nodes*/
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceArea {{{*/
+IssmDouble Tria::SurfaceArea(void){
+
+	IssmDouble S;
+	IssmDouble normal[3];
+	IssmDouble v13[3],v23[3];
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	for(int i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+
+	S = 0.5 * sqrt(normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]);
+
+	/*Return: */
+	return S;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceNormal{{{*/
+void Tria::SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]){
+
+	IssmDouble v13[3],v23[3];
+	IssmDouble normal[3];
+	IssmDouble normal_norm;
+
+	for(int i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+
+	normal_norm=sqrt( normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]);
+
+	*(surface_normal+0) = normal[0]/normal_norm;
+	*(surface_normal+1) = normal[1]/normal_norm;
+	*(surface_normal+2) = normal[2]/normal_norm;
+}
+/*}}}*/
+/*FUNCTION Tria::TimeAdapt{{{*/
+IssmDouble  Tria::TimeAdapt(void){
+
+	/*intermediary: */
+	int    i;
+	IssmDouble C,dt;
+	IssmDouble dx,dy;
+	IssmDouble maxx,minx;
+	IssmDouble maxy,miny;
+	IssmDouble maxabsvx,maxabsvy;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*get CFL coefficient:*/
+	this->parameters->FindParam(&C,TimesteppingCflCoefficientEnum);
+
+	/*Get for Vx and Vy, the max of abs value: */
+	#ifdef _HAVE_RESPONSES_
+	this->MaxAbsVx(&maxabsvx);
+	this->MaxAbsVy(&maxabsvy);
+	#else
+		_error_("ISSM was not compiled with responses compiled in, exiting!");
+	#endif
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	minx=xyz_list[0][0];
+	maxx=xyz_list[0][0];
+	miny=xyz_list[0][1];
+	maxy=xyz_list[0][1];
+
+	for(i=1;i<NUMVERTICES;i++){
+		if (xyz_list[i][0]<minx)minx=xyz_list[i][0];
+		if (xyz_list[i][0]>maxx)maxx=xyz_list[i][0];
+		if (xyz_list[i][1]<miny)miny=xyz_list[i][1];
+		if (xyz_list[i][1]>maxy)maxy=xyz_list[i][1];
+	}
+	dx=maxx-minx;
+	dy=maxy-miny;
+
+	/*CFL criterion: */
+	dt=C/(maxabsvy/dx+maxabsvy/dy);
+
+	return dt;
+}
+/*}}}*/
+/*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
+
+	/*Intermediaries*/
+	int        i                   ,j;
+	int        tria_node_ids[3];
+	int        tria_vertex_ids[3];
+	int        tria_type;
+	IssmDouble nodeinputs[3];
+	IssmDouble yts;
+	int        progstabilization,balancestabilization;
+	bool       dakota_analysis;
+
+	/*Checks if debuging*/
+	/*{{{*/
+	_assert_(iomodel->Data(MeshElementsEnum));
+	/*}}}*/
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&progstabilization,PrognosticStabilizationEnum);
+	iomodel->Constant(&balancestabilization,BalancethicknessStabilizationEnum);
+	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);
+
+	/*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
+	}
+
+	/*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
+		}
+	}
+
+	/*hooks: */
+	this->SetHookNodes(tria_node_ids,3,analysis_counter); this->nodes=NULL; //set hook to nodes, for this analysis type
+
+	/*Fill with IoModel*/
+	this->InputUpdateFromIoModel(index,iomodel);
+
+	/*Defaults if not provided in iomodel*/
+	switch(analysis_type){
+
+		case DiagnosticHorizAnalysisEnum:
+
+			/*default vx,vy and vz: either observation or 0 */
+			if(!iomodel->Data(VxEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new TriaInput(VxEnum,nodeinputs,P1Enum));
+				if(dakota_analysis) this->inputs->AddInput(new TriaInput(QmuVxEnum,nodeinputs,P1Enum));
+			}
+			if(!iomodel->Data(VyEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new TriaInput(VyEnum,nodeinputs,P1Enum));
+				if(dakota_analysis) this->inputs->AddInput(new TriaInput(QmuVyEnum,nodeinputs,P1Enum));
+			}
+			if(!iomodel->Data(VzEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new TriaInput(VzEnum,nodeinputs,P1Enum));
+				if(dakota_analysis) this->inputs->AddInput(new TriaInput(QmuVzEnum,nodeinputs,P1Enum));
+			}
+			if(!iomodel->Data(PressureEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				if(dakota_analysis){
+					this->inputs->AddInput(new TriaInput(PressureEnum,nodeinputs,P1Enum));
+					this->inputs->AddInput(new TriaInput(QmuPressureEnum,nodeinputs,P1Enum));
+				}
+			}
+			break;
+
+		default:
+			/*No update for other solution types*/
+			break;
+
+	}
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+}
+/*}}}*/
+/*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_
+/*FUNCTION Tria::AverageOntoPartition {{{*/
+void  Tria::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){
+
+	bool       already = false;
+	int        i,j;
+	int        partition[NUMVERTICES];
+	int        offsetsid[NUMVERTICES];
+	int        offsetdof[NUMVERTICES];
+	IssmDouble area;
+	IssmDouble mean;
+
+	/*First, get the area: */
+	area=this->GetArea();
+
+	/*Figure out the average for this element: */
+	this->GetVertexSidList(&offsetsid[0]);
+	this->GetVertexPidList(&offsetdof[0]);
+	mean=0;
+	for(i=0;i<NUMVERTICES;i++){
+		partition[i]=reCast<int>(qmu_part[offsetsid[i]]);
+		mean=mean+1.0/NUMVERTICES*vertex_response[offsetdof[i]];
+	}
+
+	/*Add contribution: */
+	for(i=0;i<NUMVERTICES;i++){
+		already=false;
+		for(j=0;j<i;j++){
+			if (partition[i]==partition[j]){
+				already=true;
+				break;
+			}
+		}
+		if(!already){
+			partition_contributions->SetValue(partition[i],mean*area,ADD_VAL);
+			partition_areas->SetValue(partition[i],area,ADD_VAL);
+		};
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::IceVolume {{{*/
+IssmDouble Tria::IceVolume(void){
+
+	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
+	IssmDouble base,surface,bed;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(IsOnWater())return 0;
+
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height*/
+	Input* surface_input = inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+	Input* bed_input     = inputs->GetInput(BedEnum);     _assert_(bed_input);
+	surface_input->GetInputAverage(&surface);
+	bed_input->GetInputAverage(&bed);
+
+	/*Return: */
+	return base*(surface-bed);
+}
+/*}}}*/
+/*FUNCTION Tria::MassFlux {{{*/
+IssmDouble Tria::MassFlux( IssmDouble* segment){
+
+	const int  numdofs=2;
+	int        dim;
+	IssmDouble mass_flux=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble normal[2];
+	IssmDouble length,rho_ice;
+	IssmDouble x1,y1,x2,y2,h1,h2;
+	IssmDouble vx1,vx2,vy1,vy2;
+	GaussTria* gauss_1=NULL;
+	GaussTria* gauss_2=NULL;
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+	/*First off, check that this segment belongs to this element: */
+	if (reCast<int>(*(segment+4))!=this->id)_error_("error message: segment with id " << reCast<int>(*(segment+4)) << " does not belong to element with id:" << this->id);
+
+	/*Recover segment node locations: */
+	x1=*(segment+0); y1=*(segment+1); x2=*(segment+2); y2=*(segment+3);
+
+	/*Get xyz list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*get area coordinates of 0 and 1 locations: */
+	gauss_1=new GaussTria();
+	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
+	gauss_2=new GaussTria();
+	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);
+
+	normal[0]=cos(atan2(x1-x2,y2-y1));
+	normal[1]=sin(atan2(x1-x2,y2-y1));
+
+	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));
+
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	Input* vx_input=NULL;
+	Input* vy_input=NULL;
+	if(dim==2){
+		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	}
+	else{
+		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
+	}
+
+	thickness_input->GetInputValue(&h1, gauss_1);
+	thickness_input->GetInputValue(&h2, gauss_2);
+	vx_input->GetInputValue(&vx1,gauss_1);
+	vx_input->GetInputValue(&vx2,gauss_2);
+	vy_input->GetInputValue(&vy1,gauss_1);
+	vy_input->GetInputValue(&vy2,gauss_2);
+
+	mass_flux= rho_ice*length*(  
+				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
+				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
+				);
+
+	/*clean up and return:*/
+	delete gauss_1;
+	delete gauss_2;
+	return mass_flux;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxAbsVx{{{*/
+void  Tria::MaxAbsVx(IssmDouble* pmaxabsvx){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvx=this->inputs->MaxAbs(VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvx=maxabsvx;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxAbsVy{{{*/
+void  Tria::MaxAbsVy(IssmDouble* pmaxabsvy){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvy=this->inputs->MaxAbs(VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvy=maxabsvy;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxAbsVz{{{*/
+void  Tria::MaxAbsVz(IssmDouble* pmaxabsvz){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvz=this->inputs->MaxAbs(VzEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvz=maxabsvz;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVel{{{*/
+void  Tria::MaxVel(IssmDouble* pmaxvel){
+
+	/*Get maximum:*/
+	IssmDouble maxvel=this->inputs->Max(VelEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvel=maxvel;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVx{{{*/
+void  Tria::MaxVx(IssmDouble* pmaxvx){
+
+	/*Get maximum:*/
+	IssmDouble maxvx=this->inputs->Max(VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvx=maxvx;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVy{{{*/
+void  Tria::MaxVy(IssmDouble* pmaxvy){
+
+	/*Get maximum:*/
+	IssmDouble maxvy=this->inputs->Max(VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvy=maxvy;
+
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVz{{{*/
+void  Tria::MaxVz(IssmDouble* pmaxvz){
+
+	/*Get maximum:*/
+	IssmDouble maxvz=this->inputs->Max(VzEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvz=maxvz;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVel{{{*/
+void  Tria::MinVel(IssmDouble* pminvel){
+
+	/*Get minimum:*/
+	IssmDouble minvel=this->inputs->Min(VelEnum);
+
+	/*Assign output pointers:*/
+	*pminvel=minvel;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVx{{{*/
+void  Tria::MinVx(IssmDouble* pminvx){
+
+	/*Get minimum:*/
+	IssmDouble minvx=this->inputs->Min(VxEnum);
+
+	/*Assign output pointers:*/
+	*pminvx=minvx;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVy{{{*/
+void  Tria::MinVy(IssmDouble* pminvy){
+
+	/*Get minimum:*/
+	IssmDouble minvy=this->inputs->Min(VyEnum);
+
+	/*Assign output pointers:*/
+	*pminvy=minvy;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVz{{{*/
+void  Tria::MinVz(IssmDouble* pminvz){
+
+	/*Get minimum:*/
+	IssmDouble minvz=this->inputs->Min(VzEnum);
+
+	/*Assign output pointers:*/
+	*pminvz=minvz;
+}
+/*}}}*/
+/*FUNCTION Tria::ElementResponse{{{*/
+void Tria::ElementResponse(IssmDouble* presponse,int response_enum){
+
+	switch(response_enum){
+		case MaterialsRheologyBbarEnum:
+			*presponse=this->material->GetBbar();
+			break;
+		case MaterialsRheologyZbarEnum:
+			*presponse=this->material->GetZbar();
+			break;
+		case VelEnum:{
+
+			/*Get input:*/
+			IssmDouble vel;
+			Input* vel_input;
+
+			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+			vel_input->GetInputAverage(&vel);
+
+			/*Assign output pointers:*/
+			*presponse=vel;}
+			break;
+		default:  
+			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::TotalSmb {{{*/
+IssmDouble Tria::TotalSmb(void){
+
+	/*The smb[kg yr-1] of one element is area[m2] * smb [kg m^-2 yr^-1]*/
+	IssmDouble base,smb,rho_ice;
+	IssmDouble Total_Smb=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+   if(IsOnWater())return 0;
+
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));	// area of element in m2
+
+	/*Now get the average SMB over the element*/
+	Input* smb_input = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(smb_input);
+	smb_input->GetInputAverage(&smb);																								// average smb on element in m ice s-1
+   Total_Smb=rho_ice*base*smb;																											// smb on element in kg s-1
+
+	/*Return: */
+	return Total_Smb;
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_GIA_
+/*FUNCTION Tria::GiaDeflection {{{*/
+void Tria::GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x, IssmDouble* y){
+
+	int i;
+	int gsize;
+	IssmDouble xi,yi,ri,re,area;
+	IssmDouble x0,y0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*thickness averages: */
+	IssmDouble* hes=NULL;
+	IssmDouble* times=NULL;
+	IssmDouble  currenttime;
+	int         numtimes;
+	Input* thickness_input=NULL;
+
+	/*gia solution parameters:*/
+	int cross_section_shape=0;
+
+	/*gia material parameters: */
+	IssmDouble lithosphere_shear_modulus;
+	IssmDouble lithosphere_density;
+	IssmDouble mantle_shear_modulus;
+	IssmDouble mantle_density;
+	Input* mantle_viscosity_input=NULL;
+	IssmDouble mantle_viscosity;
+	Input* lithosphere_thickness_input=NULL;
+	IssmDouble lithosphere_thickness;
+
+	/*ice properties: */
+	IssmDouble rho_ice;
+
+	/*constants: */
+	IssmDouble yts;
+
+	/*output: */
+	IssmDouble  wi;
+	IssmDouble  dwidt;
+
+	/*arguments to GiaDeflectionCorex: */
+	GiaDeflectionCoreArgs arguments;
+
+	/*how many dofs are we working with here? */
+	this->parameters->FindParam(&gsize,MeshNumberofverticesEnum);
+	this->parameters->FindParam(&yts,ConstantsYtsEnum);
+
+	/*recover gia solution parameters: */
+	this->parameters->FindParam(&cross_section_shape,GiaCrossSectionShapeEnum);
+
+	/*what time is it? :*/
+	this->parameters->FindParam(&currenttime,TimeEnum);
+
+	/*recover material parameters: */
+	lithosphere_shear_modulus=matpar->GetLithosphereShearModulus();
+	lithosphere_density=matpar->GetLithosphereDensity();
+	mantle_shear_modulus=matpar->GetMantleShearModulus();
+	mantle_density=matpar->GetMantleDensity();
+	rho_ice=matpar->GetRhoIce();
+
+	/*pull thickness averages: */
+	thickness_input=inputs->GetInput(ThicknessEnum); 
+	if (!thickness_input)_error_("thickness input needed to compute gia deflection!");
+	thickness_input->GetInputUpToCurrentTimeAverages(&hes,&times,&numtimes,currenttime);
+
+	/*recover mantle viscosity: */
+	mantle_viscosity_input=inputs->GetInput(GiaMantleViscosityEnum);
+	if (!mantle_viscosity_input)_error_("mantle viscosity input needed to compute gia deflection!");
+	mantle_viscosity_input->GetInputAverage(&mantle_viscosity);
+
+	/*recover lithosphere thickness: */
+	lithosphere_thickness_input=inputs->GetInput(GiaLithosphereThicknessEnum);
+	if (!lithosphere_thickness_input)_error_("lithosphere thickness input needed to compute gia deflection!");
+	lithosphere_thickness_input->GetInputAverage(&lithosphere_thickness);
+
+	/*pull area of this Tria: */
+	area=this->GetArea();
+
+	/*element radius: */
+	re=sqrt(area/PI);
+
+	/*figure out gravity center of our element: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	x0=(xyz_list[0][0]+xyz_list[1][0]+xyz_list[2][0])/3.0;
+	y0=(xyz_list[0][1]+xyz_list[1][1]+xyz_list[2][1])/3.0;
+
+	/*start loading GiaDeflectionCore arguments: */
+	arguments.re=re;
+	arguments.hes=hes;
+	arguments.times=times;
+	arguments.numtimes=numtimes;
+	arguments.currenttime=currenttime;
+	arguments.lithosphere_shear_modulus=lithosphere_shear_modulus;
+	arguments.lithosphere_density=lithosphere_density;
+	arguments.mantle_shear_modulus=mantle_shear_modulus;
+	arguments.mantle_viscosity=mantle_viscosity;
+	arguments.mantle_density=mantle_density;
+	arguments.lithosphere_thickness=lithosphere_thickness;
+	arguments.rho_ice=rho_ice;
+	arguments.idisk=this->id;
+	arguments.iedge=cross_section_shape;
+	arguments.yts=yts;
+
+	for(i=0;i<gsize;i++){
+		/*compute distance from the center of the tria to the vertex i: */
+		xi=x[i]; yi=y[i];
+		ri=sqrt(pow(xi-x0,2)+pow(yi-y0,2));
+
+		/*load ri onto arguments for this vertex i: */
+		arguments.ri=ri;
+
+		/*for this Tria, compute contribution to rebound at vertex i: */
+		GiaDeflectionCorex(&wi,&dwidt,&arguments);
+
+		/*plug value into solution vector: */
+		wg->SetValue(i,wi,ADD_VAL);
+		dwgdt->SetValue(i,dwidt,ADD_VAL);
+
+	}
+
+	/*Free ressources: */
+	xDelete<IssmDouble>(hes);
+	xDelete<IssmDouble>(times);
+
+	return;
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DIAGNOSTIC_
+/*FUNCTION Tria::CreateKMatrixDiagnosticMacAyeal {{{*/
+ElementMatrix* Tria::CreateKMatrixDiagnosticMacAyeal(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyealViscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticMacAyealFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixDiagnosticMacAyealViscous{{{*/
+ElementMatrix* Tria::CreateKMatrixDiagnosticMacAyealViscous(void){
+
+	/*Intermediaries*/
+	int        i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble viscosity,newviscosity,oldviscosity;
+	IssmDouble viscosity_overshoot,thickness,Jdet;
+	IssmDouble epsilon[3],oldepsilon[3];    /* epsilon=[exx,eyy,exy];    */
+	IssmDouble D_scalar;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+	int numdof   = numnodes*NDOF2;
+
+	/*Initialize Element matrix, vectors and Gaussian points*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,MacAyealApproximationEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(3*numdof);
+	IssmDouble*    Bprime = xNew<IssmDouble>(3*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(3*3);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* vx_input=inputs->GetInput(VxEnum);               _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);               _assert_(vy_input);
+	Input* vxold_input=inputs->GetInput(VxPicardEnum);      _assert_(vxold_input);
+	Input* vyold_input=inputs->GetInput(VyPicardEnum);      _assert_(vyold_input);
+	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+
+	/* 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);
+		GetBMacAyeal(&B[0], &xyz_list[0][0], gauss);
+		GetBprimeMacAyeal(&Bprime[0], &xyz_list[0][0], gauss);
+
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->GetStrainRate2d(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
+		material->GetViscosity2d(&viscosity, &epsilon[0]);
+		material->GetViscosity2d(&oldviscosity, &oldepsilon[0]);
+		thickness_input->GetInputValue(&thickness, gauss);
+
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		D_scalar=2.*newviscosity*thickness*gauss->weight*Jdet;
+		for(i=0;i<3;i++) D[i*3+i]=D_scalar;
+
+		TripleMultiply(B,3,numdof,1,
+					D,3,3,0,
+					Bprime,3,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixDiagnosticMacAyealFriction {{{*/
+ElementMatrix* Tria::CreateKMatrixDiagnosticMacAyealFriction(void){
+
+	/*Intermediaries*/
+	bool       mainlyfloating;
+	int        i,j;
+	int        analysis_type,migration_style;
+	int        point1;
+	IssmDouble alpha2;
+	IssmDouble Jdet;
+	IssmDouble fraction1,fraction2;
+	IssmDouble phi=1.0;
+	IssmDouble D_scalar;
+	IssmDouble gllevelset;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	Friction  *friction = NULL;
+	GaussTria *gauss    = NULL;
+
+	/*Return if element is inactive*/
+	if(IsFloating()) return NULL;
+
+	/*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,MacAyealApproximationEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(2*2);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	Input* surface_input=inputs->GetInput(SurfaceEnum);       _assert_(surface_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);
+	Input* gllevelset_input=NULL;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*build friction object, used later on: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/*Recover portion of element that is grounded*/
+	if(migration_style==SubelementMigrationEnum) phi=this->GetGroundedPortion(&xyz_list[0][0]);
+	if(migration_style==SubelementMigration2Enum){
+		gllevelset_input=inputs->GetInput(GLlevelsetEnum); _assert_(gllevelset_input);
+		this->GetGroundedPart(&point1,&fraction1,&fraction2,&mainlyfloating);
+		gauss=new GaussTria(point1,fraction1,fraction2,mainlyfloating,2);
+	}
+	else{
+		gauss=new GaussTria(2);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum);
+		if(migration_style==SubelementMigrationEnum) alpha2=phi*alpha2;
+		if(migration_style==SubelementMigration2Enum){
+			gllevelset_input->GetInputValue(&gllevelset, gauss);
+			if(gllevelset<0) alpha2=0;
+		}
+
+		GetBMacAyealFriction(&B[0], &xyz_list[0][0], gauss);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		D_scalar=alpha2*gauss->weight*Jdet;
+		for(i=0;i<2;i++) D[i*2+i]=D_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);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(D);
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixDiagnosticHutter{{{*/
+ElementMatrix* Tria::CreateKMatrixDiagnosticHutter(void){
+
+	/*Intermediaries*/
+	const int numdof=NUMVERTICES*NDOF2;
+	int    i,connectivity;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,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;
+	}
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorDiagnosticMacAyeal {{{*/
+ElementVector* Tria::CreatePVectorDiagnosticMacAyeal(){
+
+	/*Intermediaries */
+	int            i,j;
+	IssmDouble     driving_stress_baseline,thickness;
+	IssmDouble     Jdet;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     slope[2];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+	int numdof   = numnodes*NDOF2;
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+	GaussTria*     gauss  = new GaussTria(2);
+	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); 
+	Input* surface_input=inputs->GetInput(SurfaceEnum);     _assert_(surface_input);
+	Input* drag_input=inputs->GetInput(FrictionCoefficientEnum);_assert_(drag_input);
+
+	/* Start  looping on the number of gaussian points: */
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+		driving_stress_baseline=matpar->GetRhoIce()*matpar->GetG()*thickness;
+
+		/*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];
+			}
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorDiagnosticHutter{{{*/
+ElementVector* Tria::CreatePVectorDiagnosticHutter(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;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	n=material->GetN();
+	B=material->GetBbar();
+	Input* slopex_input=inputs->GetInput(SurfaceSlopeXEnum); _assert_(slopex_input);
+	Input* slopey_input=inputs->GetInput(SurfaceSlopeYEnum); _assert_(slopey_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);  _assert_(thickness_input);
+
+	/*Spawn 3 sing elements: */
+	gauss=new GaussTria();
+	for(i=0;i<NUMVERTICES;i++){
+
+		gauss->GaussVertex(i);
+
+		connectivity=nodes[i]->GetConnectivity();
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		slopex_input->GetInputValue(&slope[0],gauss);
+		slopey_input->GetInputValue(&slope[1],gauss);
+		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;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateJacobianDiagnosticMacayeal{{{*/
+ElementMatrix* Tria::CreateJacobianDiagnosticMacayeal(void){
+
+	/*Intermediaries */
+	int        i,j;
+	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();
+	int numdof   = numnodes*NDOF2;
+
+	/*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);
+
+	/*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* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivatives(dphi,&xyz_list[0][0],gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		material->GetViscosity2dDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
+
+		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];
+
+				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;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(dphi);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputsDiagnosticHoriz{{{*/
+void  Tria::GetSolutionFromInputsDiagnosticHoriz(Vector<IssmDouble>* solution){
+
+	IssmDouble   vx,vy;
+	int*         doflist = NULL;
+	GaussTria*   gauss   = 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 vector*/
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values = xNew<IssmDouble>(numdof);
+
+	/*Get inputs*/
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*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);
+
+		/*Recover vx and vy*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputsDiagnosticHutter{{{*/
+void  Tria::GetSolutionFromInputsDiagnosticHutter(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int        i;
+	IssmDouble     vx,vy;
+	IssmDouble     values[numdof];
+	int       *doflist = NULL;
+	GaussTria *gauss   = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Get inputs*/
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussTria();
+	for(i=0;i<NUMVERTICES;i++){
+
+		gauss->GaussVertex(i);
+
+		/*Recover vx and vy*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHoriz {{{*/
+void  Tria::InputUpdateFromSolutionDiagnosticHoriz(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);
+}
+/*}}}*/
+/*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);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_CONTROL_
+/*FUNCTION Tria::BalancethicknessMisfit{{{*/
+IssmDouble Tria::BalancethicknessMisfit(int weight_index){
+
+	/* Intermediaries */
+	IssmDouble Jelem = 0;
+	IssmDouble weight;
+	IssmDouble Jdet,temp;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dH[2];
+	IssmDouble vx,vy,H;
+	IssmDouble dvx[2],dvy[2];
+	IssmDouble dhdt,basal_melting,surface_mass_balance;
+	GaussTria *gauss = NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* weights_input              = inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* thickness_input            = inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* vx_input                   = inputs->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input                   = inputs->GetInput(VyEnum);                                 _assert_(vy_input);
+	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);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		thickness_input->GetInputValue(&H, gauss);
+		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
+		surface_mass_balance_input->GetInputValue(&surface_mass_balance,gauss);
+		basal_melting_input->GetInputValue(&basal_melting,gauss);
+		dhdt_input->GetInputValue(&dhdt,gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+
+		/*Balance thickness soft constraint J = 1/2 (div(Hv)-a)^2*/
+		temp  = vx*dH[0]+vy*dH[1]+H*(dvx[0]+dvy[1]) - (surface_mass_balance-basal_melting-dhdt);
+		Jelem+=weight*1/2*temp*temp*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::InputControlUpdate{{{*/
+void  Tria::InputControlUpdate(IssmDouble scalar,bool save_parameter){
+
+	/*Intermediary*/
+	int    num_controls;
+	int*   control_type=NULL;
+	Input* input=NULL;
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+
+		if(control_type[i]==MaterialsRheologyBbarEnum || control_type[i]==MaterialsRheologyZbarEnum){
+			input=(Input*)material->inputs->GetInput(control_type[i]); _assert_(input);
+		}
+		else{
+			input=(Input*)this->inputs->GetInput(control_type[i]);   _assert_(input);
+		}
+
+		if (input->ObjectEnum()!=ControlInputEnum){
+			_error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
+		}
+
+		((ControlInput*)input)->UpdateValue(scalar);
+		((ControlInput*)input)->Constrain();
+		if (save_parameter) ((ControlInput*)input)->SaveValue();
+
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(control_type);
+}
+/*}}}*/
+/*FUNCTION Tria::ControlInputGetGradient{{{*/
+void Tria::ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){
+
+	int vertexpidlist[NUMVERTICES];
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&vertexpidlist[0],control_index);
+	((ControlInput*)input)->GetGradient(gradient,&vertexpidlist[0]);
+
+}/*}}}*/
+/*FUNCTION Tria::ControlInputScaleGradient{{{*/
+void Tria::ControlInputScaleGradient(int enum_type,IssmDouble scale){
+
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	((ControlInput*)input)->ScaleGradient(scale);
+}/*}}}*/
+/*FUNCTION Tria::ControlInputSetGradient{{{*/
+void Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){
+
+	int    vertexpidlist[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&vertexpidlist[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
+	grad_input=new TriaInput(GradientEnum,grad_list,P1Enum);
+
+	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+/*FUNCTION Tria::Gradj {{{*/
+void  Tria::Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index){
+	/*dJ/dalpha = ∂L/∂alpha = ∂J/∂alpha + ∂/∂alpha(KU-F)*/
+
+	/*If on water, grad = 0: */
+	if(IsOnWater()) return;
+
+	/*First deal with ∂/∂alpha(KU-F)*/
+	switch(control_type){
+		case FrictionCoefficientEnum:
+			GradjDragMacAyeal(gradient,control_index);
+			break;
+		case MaterialsRheologyBbarEnum:
+			GradjBMacAyeal(gradient,control_index);
+			break;
+		case MaterialsRheologyZbarEnum:
+			GradjZMacAyeal(gradient,control_index);
+			break;
+		case BalancethicknessThickeningRateEnum:
+			GradjDhDtBalancedthickness(gradient,control_index);
+			break;
+		case VxEnum:
+			GradjVxBalancedthickness(gradient,control_index);
+			break;
+		case VyEnum:
+			GradjVyBalancedthickness(gradient,control_index);
+			break;
+		case ThicknessEnum:
+			GradjThicknessBalancethicknessSoft(gradient,control_index);
+			break;
+		default:
+			_error_("control type not supported yet: " << control_type);
+	}
+
+	/*Now deal with ∂J/∂alpha*/
+	int        *responses = NULL;
+	int         num_responses,resp;
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+		//FIXME: the control type should be checked somewhere (with respect to what variable are we taking the gradient!)
+
+		case ThicknessAbsMisfitEnum:
+		case ThicknessAbsGradientEnum:
+		case ThicknessAlongGradientEnum:
+		case ThicknessAcrossGradientEnum:
+		case BalancethicknessMisfitEnum:
+		case SurfaceAbsVelMisfitEnum:
+		case SurfaceRelVelMisfitEnum:
+		case SurfaceLogVelMisfitEnum:
+		case SurfaceLogVxVyMisfitEnum:
+		case SurfaceAverageVelMisfitEnum:
+			/*Nothing, J does not depends on the parameter being inverted for*/
+			break;
+		case DragCoefficientAbsGradientEnum:
+			GradjDragGradient(gradient,resp,control_index);
+			break;
+		case RheologyBbarAbsGradientEnum:
+			GradjBGradient(gradient,resp,control_index);
+			break;
+		default:
+			_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+
+	xDelete<int>(responses);
+}
+/*}}}*/
+/*FUNCTION Tria::GradjBGradient{{{*/
+void  Tria::GradjBGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index){
+
+	int        i;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble Jdet,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dbasis[NDOF2][NUMVERTICES];
+	IssmDouble dk[NDOF2]; 
+	IssmDouble grade_g[NUMVERTICES]={0.0};
+	GaussTria  *gauss=NULL;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GradientIndexing(&vertexpidlist[0],control_index);
+	Input* rheologyb_input=material->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+
+		/*Build alpha_complement_list: */
+		rheologyb_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for (i=0;i<NUMVERTICES;i++) grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
+	}
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjZGradient{{{*/
+void  Tria::GradjZGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index){
+
+	int        i;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble Jdet,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dbasis[NDOF2][NUMVERTICES];
+	IssmDouble dk[NDOF2]; 
+	IssmDouble grade_g[NUMVERTICES]={0.0};
+	GaussTria  *gauss=NULL;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GradientIndexing(&vertexpidlist[0],control_index);
+	Input* rheologyz_input=material->inputs->GetInput(MaterialsRheologyZbarEnum); _assert_(rheologyz_input);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+
+		/*Build alpha_complement_list: */
+		rheologyz_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for (i=0;i<NUMVERTICES;i++) grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
+	}
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjBMacAyeal{{{*/
+void  Tria::GradjBMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Intermediaries*/
+	int        i;
+	int        doflist[NUMVERTICES];
+	IssmDouble vx,vy,lambda,mu,thickness,Jdet;
+	IssmDouble viscosity_complement;
+	IssmDouble dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dB[NDOF2]; 
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble basis[3],epsilon[3];
+	IssmDouble grad[NUMVERTICES]={0.0};
+	GaussTria *gauss = NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GradientIndexing(&doflist[0],control_index);
+
+	/*Retrieve all inputs*/
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);                     _assert_(thickness_input);
+	Input* vx_input=inputs->GetInput(VxEnum);                                   _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                                   _assert_(vy_input);
+	Input* adjointx_input=inputs->GetInput(AdjointxEnum);                       _assert_(adjointx_input);
+	Input* adjointy_input=inputs->GetInput(AdjointyEnum);                       _assert_(adjointy_input);
+	Input* rheologyb_input=material->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		rheologyb_input->GetInputDerivativeValue(&dB[0],&xyz_list[0][0],gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],&xyz_list[0][0],gauss);
+		adjointy_input->GetInputDerivativeValue(&dadjy[0],&xyz_list[0][0],gauss);
+
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		material->GetViscosityComplement(&viscosity_complement,&epsilon[0]);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		/*standard gradient dJ/dki*/
+		for (i=0;i<NUMVERTICES;i++) grad[i]+=-viscosity_complement*thickness*(
+					(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
+					)*Jdet*gauss->weight*basis[i];
+	}
+
+	gradient->SetValues(NUMVERTICES,doflist,grad,ADD_VAL);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjZMacAyeal{{{*/
+void  Tria::GradjZMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Intermediaries*/
+	int        i;
+	int        doflist[NUMVERTICES];
+	IssmDouble vx,vy,lambda,mu,thickness,Jdet;
+	IssmDouble viscosity_complement;
+	IssmDouble dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dZ[NDOF2]; 
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble basis[3],epsilon[3];
+	IssmDouble grad[NUMVERTICES]={0.0};
+	GaussTria *gauss = NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GradientIndexing(&doflist[0],control_index);
+
+	/*Retrieve all inputs*/
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);                     _assert_(thickness_input);
+	Input* vx_input=inputs->GetInput(VxEnum);                                   _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                                   _assert_(vy_input);
+	Input* adjointx_input=inputs->GetInput(AdjointxEnum);                       _assert_(adjointx_input);
+	Input* adjointy_input=inputs->GetInput(AdjointyEnum);                       _assert_(adjointy_input);
+	Input* rheologyz_input=material->inputs->GetInput(MaterialsRheologyZbarEnum); _assert_(rheologyz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		rheologyz_input->GetInputDerivativeValue(&dZ[0],&xyz_list[0][0],gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],&xyz_list[0][0],gauss);
+		adjointy_input->GetInputDerivativeValue(&dadjy[0],&xyz_list[0][0],gauss);
+
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		material->GetViscosityZComplement(&viscosity_complement,&epsilon[0]);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		/*standard gradient dJ/dki*/
+		for (i=0;i<NUMVERTICES;i++) grad[i]+=-viscosity_complement*thickness*(
+					(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
+					)*Jdet*gauss->weight*basis[i];
+	}
+
+	gradient->SetValues(NUMVERTICES,doflist,grad,ADD_VAL);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjDragMacAyeal {{{*/
+void  Tria::GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+
+	int        i;
+	int        analysis_type;
+	int        vertexpidlist[NUMVERTICES];
+	int        connectivity[NUMVERTICES];
+	IssmDouble vx,vy,lambda,mu,alpha_complement,Jdet;
+	IssmDouble bed,thickness,Neff,drag;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dk[NDOF2]; 
+	IssmDouble grade_g[NUMVERTICES]={0.0};
+	IssmDouble grade_g_gaussian[NUMVERTICES];
+	IssmDouble basis[3];
+	IssmDouble epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	Friction*  friction=NULL;
+	GaussTria  *gauss=NULL;
+
+	if(IsFloating())return;
+
+	/*retrive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GradientIndexing(&vertexpidlist[0],control_index);
+	this->GetConnectivityList(&connectivity[0]);
+
+	/*Build frictoin element, needed later: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* adjointx_input=inputs->GetInput(AdjointxEnum);                   _assert_(adjointx_input);
+	Input* adjointy_input=inputs->GetInput(AdjointyEnum);                   _assert_(adjointy_input);
+	Input* vx_input=inputs->GetInput(VxEnum);                               _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                               _assert_(vy_input);
+	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		/*Build alpha_complement_list: */
+		friction->GetAlphaComplement(&alpha_complement, gauss,VxEnum,VyEnum,VzEnum);
+
+		dragcoefficient_input->GetInputValue(&drag, gauss);
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*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];
+		}
+
+		/*Add gradje_g_gaussian vector to gradje_g: */
+		for(i=0;i<NUMVERTICES;i++){
+			_assert_(!xIsNan<IssmDouble>(grade_g[i]));
+			grade_g[i]+=grade_g_gaussian[i];
+		}
+	}
+	/*Analytical gradient*/
+	//delete gauss;
+	//gauss=new GaussTria();
+	//for (int iv=0;iv<NUMVERTICES;iv++){
+	//	gauss->GaussVertex(iv);
+	//	friction->GetAlphaComplement(&alpha_complement, gauss,VxEnum,VyEnum,VzEnum);
+	//	dragcoefficient_input->GetInputValue(&drag, gauss);
+	//	adjointx_input->GetInputValue(&lambda, gauss);
+	//	adjointy_input->GetInputValue(&mu, gauss);
+	//	vx_input->GetInputValue(&vx,gauss);
+	//	vy_input->GetInputValue(&vy,gauss);
+	//	grade_g[iv] = -2*1.e+7*drag*alpha_complement*(lambda*vx+mu*vy)/((IssmDouble)connectivity[iv]);
+	//}
+	/*End Analytical gradient*/
+
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjDragGradient{{{*/
+void  Tria::GradjDragGradient(Vector<IssmDouble>* gradient, int weight_index,int control_index){
+
+	int        i;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble Jdet,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dbasis[NDOF2][NUMVERTICES];
+	IssmDouble dk[NDOF2]; 
+	IssmDouble grade_g[NUMVERTICES]={0.0};
+	GaussTria  *gauss=NULL;
+
+	/*Retrieve all inputs we will be needing: */
+	if(IsFloating())return;
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GradientIndexing(&vertexpidlist[0],control_index);
+	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                 _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+
+		/*Build alpha_complement_list: */
+		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for (i=0;i<NUMVERTICES;i++){
+			grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
+			_assert_(!xIsNan<IssmDouble>(grade_g[i]));
+		}
+	}
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjDhDtBalancedthickness{{{*/
+void  Tria::GradjDhDtBalancedthickness(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Intermediaries*/
+	int    vertexpidlist[NUMVERTICES];
+	IssmDouble lambda[NUMVERTICES];
+	IssmDouble gradient_g[NUMVERTICES];
+
+	/*Compute Gradient*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+	GetInputListOnVertices(&lambda[0],AdjointEnum);
+	for(int i=0;i<NUMVERTICES;i++) gradient_g[i]=-lambda[i];
+
+	gradient->SetValues(NUMVERTICES,vertexpidlist,gradient_g,INS_VAL);
+}
+/*}}}*/
+/*FUNCTION Tria::GradjVxBalancedthickness{{{*/
+void  Tria::GradjVxBalancedthickness(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Intermediaries*/
+	int        i;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble thickness,Jdet;
+	IssmDouble basis[3];
+	IssmDouble Dlambda[2],dp[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble grade_g[NUMVERTICES] = {0.0};
+	GaussTria *gauss                = NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* adjoint_input=inputs->GetInput(AdjointEnum);     _assert_(adjoint_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		adjoint_input->GetInputDerivativeValue(&Dlambda[0],&xyz_list[0][0],gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+
+		for(i=0;i<NUMVERTICES;i++) grade_g[i]+=thickness*Dlambda[0]*Jdet*gauss->weight*basis[i];
+	}
+
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjVyBalancedthickness{{{*/
+void  Tria::GradjVyBalancedthickness(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Intermediaries*/
+	int        i;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble thickness,Jdet;
+	IssmDouble basis[3];
+	IssmDouble Dlambda[2],dp[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble grade_g[NUMVERTICES] = {0.0};
+	GaussTria *gauss                = NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* adjoint_input=inputs->GetInput(AdjointEnum);     _assert_(adjoint_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		adjoint_input->GetInputDerivativeValue(&Dlambda[0],&xyz_list[0][0],gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+
+		for(i=0;i<NUMVERTICES;i++) grade_g[i]+=thickness*Dlambda[1]*Jdet*gauss->weight*basis[i];
+	}
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjThicknessBalancethicknessSoft{{{*/
+void  Tria::GradjThicknessBalancethicknessSoft(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Intermediaries */
+	int         i,resp;
+	int         vertexpidlist[NUMVERTICES];
+	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;
+	IssmDouble  dvx[2],dvy[2];
+	IssmDouble dhdt,basal_melting,surface_mass_balance;
+	GaussTria *gauss     = NULL;
+	int       *responses = NULL;
+	IssmDouble grade_g[NUMVERTICES] = {0.0};
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*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* thickness_input            = inputs->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+	Input* thicknessobs_input         = inputs->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
+	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* 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);
+
+	/* Start  looping on the number of gaussian points: */
+	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);
+		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
+		thicknessobs_input->GetInputValue(&thicknessobs, gauss);
+
+		/*Loop over all requested responses*/
+		for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+
+			case ThicknessAbsMisfitEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				for(i=0;i<NUMVERTICES;i++) grade_g[i]+= (thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
+				break;
+			case ThicknessAbsGradientEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*dH[0]*dbasis[0][i]*Jdet*gauss->weight;
+				for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*dH[1]*dbasis[1][i]*Jdet*gauss->weight;
+				break;
+			case ThicknessAlongGradientEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vel = sqrt(vx*vx+vy*vy);
+				vx  = vx/(vel+1.e-9);
+				vy  = vy/(vel+1.e-9);
+				for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0][i]*vx+dbasis[1][i]*vy)*Jdet*gauss->weight;
+				break;
+			case ThicknessAcrossGradientEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vel = sqrt(vx*vx+vy*vy);
+				vx  = vx/(vel+1.e-9);
+				vy  = vy/(vel+1.e-9);
+				for(i=0;i<NUMVERTICES;i++) grade_g[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0][i]*(-vy)+dbasis[1][i]*vx)*Jdet*gauss->weight;
+				break;
+			case BalancethicknessMisfitEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				surface_mass_balance_input->GetInputValue(&surface_mass_balance,gauss);
+				basal_melting_input->GetInputValue(&basal_melting,gauss);
+				dhdt_input->GetInputValue(&dhdt,gauss);
+				vx_input->GetInputValue(&vx,gauss);
+				vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+				for(i=0;i<NUMVERTICES;i++){
+					grade_g[i]+= - weight*Jdet*gauss->weight*(
+								(vx*dH[0]+vy*dH[1] + thickness*(dvx[0]+dvy[1]))*(vx*dbasis[0][i]+ vy*dbasis[1][i] + basis[i]*(dvx[0]+dvy[1]))
+								-(surface_mass_balance-basal_melting-dhdt)*(vx*dbasis[0][i]+ vy*dbasis[1][i] + basis[i]*(dvx[0]+dvy[1]))
+								);
+				}
+				break;
+			default:
+				_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+		}
+	}
+
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(responses);
+}
+/*}}}*/
+/*FUNCTION Tria::GradientIndexing{{{*/
+void  Tria::GradientIndexing(int* indexing,int control_index){
+
+	/*Get some parameters*/
+	int num_controls;
+	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+
+	/*get gradient indices*/
+	for(int i=0;i<NUMVERTICES;i++){
+		indexing[i]=num_controls*this->vertices[i]->Pid() + control_index;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::RheologyBbarAbsGradient{{{*/
+IssmDouble Tria::RheologyBbarAbsGradient(int weight_index){
+
+	/* Intermediaries */
+	IssmDouble Jelem = 0;
+	IssmDouble weight;
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dp[NDOF2];
+	GaussTria *gauss = NULL;
+
+	/*retrieve parameters and inputs*/
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* weights_input  =inputs->GetInput(InversionCostFunctionsCoefficientsEnum);              _assert_(weights_input);
+	Input* rheologyb_input=material->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		rheologyb_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+
+		/*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;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceAverageVelMisfit {{{*/
+IssmDouble Tria::SurfaceAverageVelMisfit(int weight_index){
+
+	IssmDouble Jelem=0,S,Jdet;
+	IssmDouble misfit;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	GaussTria *gauss=NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	inputs->GetInputValue(&S,SurfaceAreaEnum);
+	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);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(3);
+	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*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Compute SurfaceAverageVelMisfitEnum:
+		 *
+		 *      1                    2              2
+		 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
+		 *      S                obs            obs
+		 */
+		misfit=1/S*sqrt( pow(vx-vxobs,2) + pow(vy-vyobs,2));
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean-up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceLogVelMisfit {{{*/
+IssmDouble Tria::SurfaceLogVelMisfit(int weight_index){
+
+	IssmDouble Jelem=0;
+	IssmDouble misfit,Jdet;
+	IssmDouble epsvel=2.220446049250313e-16;
+	IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	IssmDouble velocity_mag,obs_velocity_mag;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	GaussTria *gauss=NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	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);
+
+	/* 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*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Compute SurfaceLogVelMisfit:
+		 *        4         [        vel + eps     ] 2
+		 * J = 4 \bar{v}^2 | log ( -----------  ) |  
+		 *                 [       vel   + eps    ]
+		 *                            obs
+		 */
+		velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
+		obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
+		misfit=4*pow(meanvel,2)*pow(log(velocity_mag/obs_velocity_mag),2);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean-up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceLogVxVyMisfit {{{*/
+IssmDouble Tria::SurfaceLogVxVyMisfit(int weight_index){
+
+	int        fit=-1;
+	IssmDouble Jelem=0, S=0;
+	IssmDouble epsvel=2.220446049250313e-16;
+	IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	IssmDouble misfit, Jdet;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	GaussTria *gauss=NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	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);
+
+	/* 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*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Compute SurfaceRelVelMisfit:
+		 *
+		 *      1            [        |u| + eps     2          |v| + eps     2  ]
+		 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
+		 *      2            [       |u    |+ eps              |v    |+ eps     ]
+		 *                              obs                       obs
+		 */
+		misfit=0.5*pow(meanvel,2)*(
+					pow(log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)),2) +
+					pow(log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)),2) );
+
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean-up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceAbsVelMisfit {{{*/
+IssmDouble Tria::SurfaceAbsVelMisfit(int weight_index){
+
+	IssmDouble Jelem=0;
+	IssmDouble misfit,Jdet;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	GaussTria *gauss=NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	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);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Compute SurfaceAbsVelMisfitEnum:
+		 *
+		 *      1  [           2              2 ]
+		 * J = --- | (u - u   )  +  (v - v   )  |
+		 *      2  [       obs            obs   ]
+		 *
+		 */
+		misfit=0.5*( pow(vx-vxobs,2) + pow(vy-vyobs,2) );
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceRelVelMisfit {{{*/
+IssmDouble Tria::SurfaceRelVelMisfit(int weight_index){
+
+	IssmDouble  Jelem=0;
+	IssmDouble  scalex=1,scaley=1;
+	IssmDouble  misfit,Jdet;
+	IssmDouble  epsvel=2.220446049250313e-16;
+	IssmDouble  meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	IssmDouble  vx,vy,vxobs,vyobs,weight;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	GaussTria *gauss=NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	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);
+
+	/* 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*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Compute SurfaceRelVelMisfit:
+		 *                        
+		 *      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                      
+		 */
+		scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+		scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
+		misfit=0.5*(scalex*pow((vx-vxobs),2)+scaley*pow((vy-vyobs),2));
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAbsGradient{{{*/
+IssmDouble Tria::ThicknessAbsGradient(int weight_index){
+
+	/* Intermediaries */
+	IssmDouble Jelem = 0;
+	IssmDouble weight;
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dp[NDOF2];
+	GaussTria *gauss = NULL;
+
+	/*retrieve parameters and inputs*/
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* weights_input  =inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+
+		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
+		Jelem+=weight*1/2*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAlongGradient{{{*/
+IssmDouble Tria::ThicknessAlongGradient(int weight_index){
+
+	/* Intermediaries */
+	IssmDouble  Jelem = 0;
+	IssmDouble  weight;
+	IssmDouble  Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  dp[NDOF2];
+	IssmDouble  vx,vy,vel;
+	GaussTria  *gauss                    = NULL;
+
+	/*retrieve parameters and inputs*/
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* weights_input  = inputs->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* thickness_input= inputs->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+	Input* vx_input       = inputs->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input       = inputs->GetInput(VyEnum);                                 _assert_(vy_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel = sqrt(vx*vx+vy*vy);
+		vx  = vx/(vel+1.e-9);
+		vy  = vy/(vel+1.e-9);
+
+		/*J = 1/2 ( vx*dH/dx + vy*dH/dy )^2 */
+		Jelem+=weight*1/2*(vx*dp[0] + vy*dp[1])*(vx*dp[0] + vy*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAcrossGradient{{{*/
+IssmDouble Tria::ThicknessAcrossGradient(int weight_index){
+
+	/* Intermediaries */
+	IssmDouble  Jelem = 0;
+	IssmDouble  weight;
+	IssmDouble  Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  dp[NDOF2];
+	IssmDouble  vx,vy,vel;
+	GaussTria  *gauss                    = NULL;
+
+	/*retrieve parameters and inputs*/
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* weights_input  = inputs->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* thickness_input= inputs->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+	Input* vx_input       = inputs->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input       = inputs->GetInput(VyEnum);                                 _assert_(vy_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel = sqrt(vx*vx+vy*vy);
+		vx  = vx/(vel+1.e-9);
+		vy  = vy/(vel+1.e-9);
+
+		/*J = 1/2 ( -vy*dH/dx + vx*dH/dy )^2 */
+		Jelem+=weight*1/2*(-vy*dp[0] + vx*dp[1])*(-vy*dp[0] + vx*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAbsMisfit {{{*/
+IssmDouble Tria::ThicknessAbsMisfit(int weight_index){
+
+	/*Intermediaries*/
+	IssmDouble thickness,thicknessobs,weight;
+	IssmDouble Jdet;
+	IssmDouble Jelem = 0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	GaussTria *gauss = NULL;
+	IssmDouble dH[2];
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* thickness_input   =inputs->GetInput(ThicknessEnum);   _assert_(thickness_input);
+	Input* thicknessobs_input=inputs->GetInput(InversionThicknessObsEnum);_assert_(thicknessobs_input);
+	Input* weights_input     =inputs->GetInput(InversionCostFunctionsCoefficientsEnum);     _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get parameters at gauss point*/
+		thickness_input->GetInputValue(&thickness,gauss);
+		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
+		thicknessobs_input->GetInputValue(&thicknessobs,gauss);
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+
+		/*compute ThicknessAbsMisfit*/
+		Jelem+=0.5*(thickness-thicknessobs)*(thickness-thicknessobs)*weight*Jdet*gauss->weight;
+	}
+
+	/* clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorAdjointBalancethickness{{{*/
+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       *responses = NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*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* thickness_input    = inputs->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+	Input* thicknessobs_input = inputs->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
+	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);
+
+	/* Start  looping on the number of gaussian points: */
+	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);
+		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
+		thicknessobs_input->GetInputValue(&thicknessobs, gauss);
+
+		/*Loop over all requested responses*/
+		for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+
+			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];
+				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;
+				break;
+			case ThicknessAlongGradientEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vel = sqrt(vx*vx+vy*vy);
+				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;
+				break;
+			case ThicknessAcrossGradientEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vel = sqrt(vx*vx+vy*vy);
+				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;
+				break;
+			default:
+				_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(responses);
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorAdjointHoriz{{{*/
+ElementVector* Tria::CreatePVectorAdjointHoriz(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*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);
+
+	/*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*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+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*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+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*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+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*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+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*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet*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*/
+	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;
+}
+/*}}}*/
+/*FUNCTION Tria::DragCoefficientAbsGradient{{{*/
+IssmDouble Tria::DragCoefficientAbsGradient(int weight_index){
+
+	/* Intermediaries */
+	IssmDouble Jelem = 0;
+	IssmDouble weight;
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dp[NDOF2];
+	GaussTria *gauss = NULL;
+
+	/*retrieve parameters and inputs*/
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);         _assert_(weights_input);
+	Input* drag_input   =inputs->GetInput(FrictionCoefficientEnum); _assert_(drag_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		drag_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+
+		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
+		Jelem+=weight*1/2*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixAdjointBalancethickness {{{*/
+ElementMatrix* Tria::CreateKMatrixAdjointBalancethickness(void){
+
+	ElementMatrix* Ke=NULL;
+
+	/*Get Element Matrix of the forward model*/
+	switch(GetElementType()){
+		case P1Enum:
+			Ke=CreateKMatrixBalancethickness_CG();
+			break;
+		case P1DGEnum:
+			Ke=CreateKMatrixBalancethickness_DG();
+			break;
+		default:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+
+	/*Transpose and return Ke*/
+	Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixAdjointMacAyeal{{{*/
+ElementMatrix* Tria::CreateKMatrixAdjointMacAyeal(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*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)*/
+	parameters->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
+	ElementMatrix* Ke=CreateKMatrixDiagnosticMacAyeal();
+	if(incomplete_adjoint) return Ke;
+
+	/*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* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivatives(&dphi[0][0],&xyz_list[0][0],gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		material->GetViscosity2dDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
+
+		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;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	//Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionAdjointHoriz {{{*/
+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: */
+	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<NUMVERTICES;i++){
+		lambdax[i]=values[i*NDOF2+0];
+		lambday[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new TriaInput(AdjointxEnum,lambdax,P1Enum));
+	this->inputs->AddInput(new TriaInput(AdjointyEnum,lambday,P1Enum));
+
+	/*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<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::GetVectorFromControlInputs{{{*/
+void  Tria::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){
+
+	int vertexpidlist[NUMVERTICES];
+	Input *input=NULL;
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get input (either in element or material)*/
+	if(control_enum==MaterialsRheologyBbarEnum || control_enum==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(control_enum); _assert_(input);
+	}
+	else{
+		input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	}
+
+	/*Check that it is a ControlInput*/
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
+}
+/*}}}*/
+/*FUNCTION Tria::SetControlInputsFromVector{{{*/
+void  Tria::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){
+
+	IssmDouble  values[NUMVERTICES];
+	int     vertexpidlist[NUMVERTICES];
+	Input  *input     = NULL;
+	Input  *new_input = NULL;
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get values on vertices*/
+	for (int i=0;i<NUMVERTICES;i++){
+		values[i]=vector[vertexpidlist[i]];
+	}
+	new_input = new TriaInput(control_enum,values,P1Enum);
+
+	if(control_enum==MaterialsRheologyBbarEnum || control_enum==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(control_enum); _assert_(input);
+	}
+	else{
+		input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	}
+
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->SetInput(new_input);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_THERMAL_
+/*FUNCTION Tria::CreateKMatrixMelting {{{*/
+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);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	latentheat=matpar->GetLatentHeat();
+	heatcapacity=matpar->GetHeatCapacity();
+
+	/* Start looping on the number of gauss  (nodes on the bedrock) */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetNodalFunctions(&basis[0],gauss);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0], gauss);
+
+		D_scalar=latentheat/heatcapacity*gauss->weight*Jdet;
+
+		TripleMultiply(&basis[0],numdof,1,0,
+					&D_scalar,1,1,0,
+					&basis[0],1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_HYDROLOGY_
+/*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;
+}
+/*}}}*/
+/*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;
+}/*}}}*/
+/*FUNCTION Tria::CreateHydrologyWaterVelocityInput {{{*/
+void Tria::CreateHydrologyWaterVelocityInput(void){
+
+	/*material parameters: */
+	IssmDouble mu_water;
+	IssmDouble VelocityFactor;  // This factor represents the number 12 in laminar flow velocity which can vary by differnt hydrology.CR
+	IssmDouble n_man,CR;
+	IssmDouble w;
+	IssmDouble rho_ice, rho_water, g;
+	IssmDouble dsdx,dsdy,dbdx,dbdy;
+	IssmDouble vx[NUMVERTICES];
+	IssmDouble vy[NUMVERTICES];
+	GaussTria *gauss = NULL;
+
+	/*Retrieve all inputs and parameters*/
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+	g=matpar->GetG();
+	CR=matpar->GetHydrologyCR(); // To have Lebrocq equavalent equation: CR=0.01,n_man=0.02
+	n_man=matpar->GetHydrologyN(); 
+	mu_water=matpar->GetMuWater();
+	Input* surfaceslopex_input=inputs->GetInput(SurfaceSlopeXEnum); _assert_(surfaceslopex_input);
+	Input* surfaceslopey_input=inputs->GetInput(SurfaceSlopeYEnum); _assert_(surfaceslopey_input);
+	Input* bedslopex_input=inputs->GetInput(BedSlopeXEnum);         _assert_(bedslopex_input);
+	Input* bedslopey_input=inputs->GetInput(BedSlopeYEnum);         _assert_(bedslopey_input);
+	Input* watercolumn_input=inputs->GetInput(WatercolumnEnum);     _assert_(watercolumn_input);
+
+	/* compute VelocityFactor */
+	VelocityFactor= n_man*CR*CR*rho_water*g/mu_water;
+
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+		surfaceslopex_input->GetInputValue(&dsdx,gauss);
+		surfaceslopey_input->GetInputValue(&dsdy,gauss);
+		bedslopex_input->GetInputValue(&dbdx,gauss);
+		bedslopey_input->GetInputValue(&dbdy,gauss);
+		watercolumn_input->GetInputValue(&w,gauss);
+
+		/* Water velocity x and y components */
+	//	vx[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+	//	vy[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+		vx[iv]= - w*w/(VelocityFactor* mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+		vy[iv]= - w*w/(VelocityFactor* mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+	}
+
+	/*clean-up*/
+	delete gauss;
+
+	/*Add to inputs*/
+	this->inputs->AddInput(new TriaInput(HydrologyWaterVxEnum,vx,P1Enum));
+	this->inputs->AddInput(new TriaInput(HydrologyWaterVyEnum,vy,P1Enum));
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixHydrologyShreve{{{*/
+ElementMatrix* Tria::CreateKMatrixHydrologyShreve(void){
+
+	/*Constants*/
+	const int  numdof=NDOF1*NUMVERTICES;
+
+/*Intermediaries */
+	IssmDouble diffusivity;
+	IssmDouble Jdettria,DL_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*/
+	CreateHydrologyWaterVelocityInput();
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&diffusivity,HydrologyshreveStabilizationEnum);
+	Input* vx_input=inputs->GetInput(HydrologyWaterVxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(HydrologyWaterVyEnum); _assert_(vy_input);
+	h=sqrt(2*this->GetArea());
+
+/* Start  looping on the number of gaussian points: */
+	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);
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		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);
+
+		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);
+
+		/*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*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixHydrologyDCInefficient{{{*/
+ElementMatrix* Tria::CreateKMatrixHydrologyDCInefficient(void){
+
+	/*constants: */
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/* Intermediaries */
+	IssmDouble  D_scalar,Jdet;
+	IssmDouble 	sediment_transmitivity,dt;
+	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);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	sediment_storing       = matpar->GetSedimentStoring();
+	sediment_transmitivity = matpar->GetSedimentTransmitivity();
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Diffusivity*/
+		D_scalar=sediment_transmitivity*gauss->weight*Jdet;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar=D_scalar*dt;
+		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);
+
+		/*Transient*/
+		if(reCast<bool,IssmDouble>(dt)){
+			GetNodalFunctions(&basis[0],gauss);
+			D_scalar=sediment_storing*gauss->weight*Jdet;
+
+			TripleMultiply(&basis[0],numdof,1,0,
+						&D_scalar,1,1,0,
+						&basis[0],1,numdof,0,
+						&Ke->values[0],1);
+		}
+	}
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixHydrologyDCEfficient{{{*/
+ElementMatrix* Tria::CreateKMatrixHydrologyDCEfficient(void){
+
+	/*constants: */
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/* Intermediaries */
+	IssmDouble  D_scalar,Jdet;
+	IssmDouble 	epl_transmitivity,dt;
+	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*/
+	if(!this->AllActive()){
+		return NULL;
+	}
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	epl_storing       = matpar->GetEplStoring();
+	epl_transmitivity = matpar->GetEplTransmitivity();
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Diffusivity*/
+		D_scalar=epl_transmitivity*gauss->weight*Jdet;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar=D_scalar*dt;
+		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);
+
+		/*Transient*/
+		if(reCast<bool,IssmDouble>(dt)){
+			GetNodalFunctions(&basis[0],gauss);
+			D_scalar=epl_storing*gauss->weight*Jdet;
+
+			TripleMultiply(&basis[0],numdof,1,0,
+						&D_scalar,1,1,0,
+						&basis[0],1,numdof,0,
+						&Ke->values[0],1);
+		}
+	}
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorHydrologyShreve {{{*/
+ElementVector* Tria::CreatePVectorHydrologyShreve(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j;
+	IssmDouble Jdettria,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;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum); _assert_(basal_melting_input);
+	Input* old_watercolumn_input=inputs->GetInput(WaterColumnOldEnum);         _assert_(old_watercolumn_input);
+
+	/*Initialize basal_melting_correction_g to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	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, gauss);
+
+		basal_melting_input->GetInputValue(&basal_melting_g,gauss);
+		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];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorHydrologyDCInefficient {{{*/
+ElementVector* Tria::CreatePVectorHydrologyDCInefficient(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dt,scalar,water_head;
+	IssmDouble water_load,transfer;
+	IssmDouble sediment_storing;
+	IssmDouble basis[numdof];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	sediment_storing = matpar->GetSedimentStoring();
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* water_input=inputs->GetInput(BasalforcingsMeltingRateEnum);  _assert_(water_input);
+	Input* transfer_input=inputs->GetInput(WaterTransferEnum);  _assert_(transfer_input);
+	Input* old_wh_input=NULL; 
+
+	if(reCast<bool,IssmDouble>(dt)){
+		old_wh_input=inputs->GetInput(SedimentHeadOldEnum); _assert_(old_wh_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		/*Loading term*/
+		water_input->GetInputValue(&water_load,gauss);
+		transfer_input->GetInputValue(&transfer,gauss);
+		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];
+
+		/*Transient term*/
+		if(reCast<bool,IssmDouble>(dt)){
+			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];
+		}
+	}
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorHydrologyDCEfficient {{{*/
+ElementVector* Tria::CreatePVectorHydrologyDCEfficient(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	IssmDouble connectivity;
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dt,scalar,water_head;
+	IssmDouble transfer,residual;
+	IssmDouble epl_storing;
+	IssmDouble basis[numdof];
+	GaussTria* gauss=NULL;
+
+	/*Check that all nodes are active, else return empty matrix*/
+	if(!this->AllActive()){
+		return NULL;
+	}
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	epl_storing = matpar->GetEplStoring();
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* residual_input=inputs->GetInput(SedimentHeadResidualEnum);  _assert_(residual_input);
+	Input* transfer_input=inputs->GetInput(WaterTransferEnum);  _assert_(transfer_input);
+	Input* old_wh_input=NULL; 
+
+	if(reCast<bool,IssmDouble>(dt)){
+		old_wh_input=inputs->GetInput(EplHeadOldEnum); _assert_(old_wh_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		/*Loading term*/
+		transfer_input->GetInputValue(&transfer,gauss);
+		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];
+
+		/*Transient term*/
+		if(reCast<bool,IssmDouble>(dt)){
+			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];
+		}
+	}
+	delete gauss;
+	
+	/*	Add residual if necessary*/
+	gauss=new GaussTria();
+	for(int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		connectivity = IssmDouble(nodes[iv]->GetConnectivity());
+		residual_input->GetInputValue(&residual,gauss);
+		pe->values[iv]+=residual/connectivity;
+	}
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*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: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Get inputs*/
+	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
+
+	/*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);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionHydrologyShreve{{{*/
+void  Tria::InputUpdateFromSolutionHydrologyShreve(IssmDouble* solution){
+
+	/*Intermediaries*/
+	const int   numdof         = NDOF1 *NUMVERTICES;
+	int        *doflist        = NULL;
+	IssmDouble  values[numdof];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+		if (values[i]<10e-10) values[i]=10e-10; //correcting the water column to positive values
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaInput(WatercolumnEnum,values,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionHydrologyDCInefficient{{{*/
+void  Tria::InputUpdateFromSolutionHydrologyDCInefficient(IssmDouble* solution){
+
+	/*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: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*If converged keep the residual in mind*/
+	this->inputs->GetInputValue(&converged,ConvergedEnum);
+
+	/*Get inputs*/
+	if(converged){
+		this->parameters->FindParam(&kmax,HydrologySedimentKmaxEnum);
+		this->parameters->FindParam(&penalty_factor,HydrologydcPenaltyFactorEnum);
+		
+		kappa=kmax*pow(10.,penalty_factor);
+		
+		for(int i=0;i<NUMVERTICES;i++){
+			this->GetHydrologyDCInefficientHmax(&h_max,nodes[i]);
+			if(values[i]>h_max){
+				residual[i]=kappa*(values[i]-h_max);
+			}
+			else{
+				residual[i]=0.0;
+			}
+		}
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaInput(SedimentHeadEnum,values,P1Enum));
+	this->inputs->AddInput(new TriaInput(SedimentHeadResidualEnum,residual,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::GetHydrologyDCInefficientHmax{{{*/
+void  Tria::GetHydrologyDCInefficientHmax(IssmDouble* ph_max, Node* innode){
+
+		int        hmax_flag;
+		IssmDouble h_max;
+		IssmDouble rho_ice,rho_water;
+		IssmDouble thickness,bed;
+		/*Get the flag to the limitation method*/
+		this->parameters->FindParam(&hmax_flag,HydrologydcSedimentlimitFlagEnum);
+
+		/*Switch between the different cases*/
+		switch(hmax_flag){
+			case 0:
+				h_max=1.0e+10;
+				break;
+			case 1:
+				parameters->FindParam(&h_max,HydrologydcSedimentlimitEnum);
+				break;
+			case 2:
+				rho_ice=matpar->GetRhoIce();
+				rho_water=matpar->GetRhoFreshwater();
+				this->GetInputValue(&thickness,innode,ThicknessEnum);
+				this->GetInputValue(&bed,innode,BedEnum);
+				h_max=((rho_ice*thickness)/rho_water)+bed;
+				break;
+			case 3:
+				_error_("Using normal stress  not supported yet");
+				break;
+			default:
+				_error_("no case higher than 3 for SedimentlimitFlag");
+		}
+		/*Assign output pointer*/
+		*ph_max=h_max;
+}
+/*}}}*/
+/*FUNCTION Tria::GetHydrologyTransfer{{{*/
+void  Tria::GetHydrologyTransfer(Vector<IssmDouble>* transfer){
+
+	const int  numdof         = NDOF1 *NUMVERTICES;
+	int        *doflist       = NULL;
+	bool       isefficientlayer;
+	int        transfermethod;
+	IssmDouble sed_trans,sed_thick;
+	IssmDouble leakage,h_max;
+	IssmDouble wh_trans;
+	IssmDouble activeEpl[numdof];
+	IssmDouble eplstoring[numdof],sedstoring[numdof];
+	IssmDouble epl_head[numdof],sed_head[numdof];
+
+	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*/
+		this->parameters->FindParam(&transfermethod,HydrologydcTransferFlagEnum);
+
+		/*Switch between the different transfer methods cases*/
+		switch(transfermethod){
+		case 0:
+			/*Just keepping the transfer to zero, should be OK with the initial value of transfer*/
+			break;
+		case 1:
+
+			GetInputListOnVertices(&activeEpl[0],HydrologydcMaskEplactiveEnum);
+			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*/
+				if(activeEpl[i]==0.0){
+					wh_trans=0.0;
+				}
+				else{
+					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]);
+						if(sed_head[i]>=h_max)wh_trans=0.0;
+					}
+					/*EPL head lower than sediment head, transfer from the sediment to the epl*/
+					else if(epl_head[i]<sed_head[i]){
+						wh_trans=sedstoring[i]*sed_trans*(epl_head[i]-sed_head[i])/(leakage*sed_thick);				
+					}
+				}
+				/*Assign output pointer*/
+				transfer->SetValue(doflist[i],wh_trans,INS_VAL);
+			}
+			break;
+		default:
+			_error_("no case higher than 1 for the Transfer method");
+		}
+	}
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::HydrologyEPLGetActive {{{*/
+void Tria::HydrologyEPLGetActive(Vector<IssmDouble>* active_vec){
+
+	/*Constants*/
+	const int  numnodes = NUMVERTICES;
+	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++){
+			active_vec->SetValue(nodes[i]->Sid(),1.,INS_VAL);
+		}
+	}
+	else{
+		/*Do not do anything: at least one node is active for this element but this element is not solved for*/
+	}
+	
+}
+/*}}}*/
+/*FUNCTION Tria::HydrologyEPLGetMask{{{*/
+void  Tria::HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask){
+
+	/*Intermediaries*/
+	int         i,j;
+	const int   numdof         = NDOF1 *NUMVERTICES;
+	IssmDouble  h_max;
+	IssmDouble  sedheadmin;
+	IssmDouble  old_active[numdof];
+	IssmDouble  sedhead[numdof];
+	IssmDouble  eplhead[numdof];
+	IssmDouble  residual[numdof];
+
+	GetInputListOnVertices(&old_active[0],HydrologydcMaskEplactiveEnum);	
+	GetInputListOnVertices(&sedhead[0],SedimentHeadEnum);
+	GetInputListOnVertices(&eplhead[0],EplHeadEnum);
+	GetInputListOnVertices(&residual[0],SedimentHeadResidualEnum);
+
+	/*Get minimum sediment head*/
+	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 */
+		if(residual[i]>0.){
+			vec_mask->SetValue(nodes[i]->Sid(),1.,INS_VAL);
+		}
+		
+		/*If mask was alread one, keep one*/
+		else if(old_active[i]>0.){
+			vec_mask->SetValue(nodes[i]->Sid(),1.,INS_VAL);
+		}
+
+		/*Increase of the efficient system is needed if the epl head reach the maximum value (sediment max value for now)*/
+		this->GetHydrologyDCInefficientHmax(&h_max,nodes[i]);
+		if(eplhead[i]>=h_max && this->AnyActive()){
+			for(j=0;j<numdof;j++){
+				if(old_active[j]>0.){
+					vec_mask->SetValue(nodes[i]->Sid(),1.,INS_VAL);
+				}
+				/*Increase of the domain is on the downstream node in term of sediment head*/
+				if(sedhead[j] == sedheadmin){
+					vec_mask->SetValue(nodes[j]->Sid(),1.,INS_VAL);
+					//	break;
+				}
+			}
+		}
+	}
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_PROGNOSTIC_
+/*FUNCTION Tria::CreateKMatrixPrognostic {{{*/
+ElementMatrix* Tria::CreateKMatrixPrognostic(void){
+
+	switch(GetElementType()){
+		case P1Enum:
+			return CreateKMatrixPrognostic_CG();
+		case P1DGEnum:
+			return CreateKMatrixPrognostic_DG();
+		default:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixPrognostic_CG {{{*/
+ElementMatrix* Tria::CreateKMatrixPrognostic_CG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        dim;
+	IssmDouble Jdettria,DL_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);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	this->parameters->FindParam(&stabilization,PrognosticStabilizationEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(dim==2){
+		vxaverage_input=inputs->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		vxaverage_input=inputs->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyAverageEnum); _assert_(vyaverage_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(&Jdettria, &xyz_list[0][0],gauss);
+		GetNodalFunctions(&basis[0],gauss);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		vxaverage_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		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,
+					&Ke->values[0],1);
+
+		GetBPrognostic(&B[0][0], &xyz_list[0][0], gauss);
+		GetBprimePrognostic(&Bprime[0][0], &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);
+
+		if(stabilization==2){
+			/*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;
+		}
+		else if(stabilization==1){
+			/*MacAyeal*/
+			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);
+		}
+		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,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixPrognostic_DG {{{*/
+ElementMatrix* Tria::CreateKMatrixPrognostic_DG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*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);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(dim==2){
+		vxaverage_input=inputs->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		vxaverage_input=inputs->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		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,
+					&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,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	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;
+
+	/*Intermediaries */
+	IssmDouble Jdettria,dt;
+	IssmDouble surface_mass_balance_g,basal_melting_g,basal_melting_correction_g,thickness_g;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble basis[NUMVERTICES];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*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!:*/
+	/* Start  looping on the number of gaussian points: */
+	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);
+		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];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorPrognostic_DG {{{*/
+ElementVector* Tria::CreatePVectorPrognostic_DG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	IssmDouble Jdettria,dt;
+	IssmDouble surface_mass_balance_g,basal_melting_g,thickness_g;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble basis[NUMVERTICES];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*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);
+
+	/* Start  looping on the number of gaussian points: */
+	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];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DAKOTA_
+/*FUNCTION Tria::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);{{{*/
+void  Tria::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
+
+	int i,j;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*New TriaInput*/
+			IssmDouble values[3];
+
+			/*Get values on the 3 vertices*/
+			for (i=0;i<3;i++){
+				values[i]=vector[this->vertices[i]->Sid()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
+			}
+
+			/*Branch on the specified type of update: */
+			switch(name){
+				case ThicknessEnum:
+					IssmDouble  thickness[3];
+					IssmDouble  thickness_init[3];
+					IssmDouble  hydrostatic_ratio[3];
+					IssmDouble  surface[3];
+					IssmDouble  bed[3];
+
+					/*retrieve inputs: */
+					GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
+					GetInputListOnVertices(&hydrostatic_ratio[0],GeometryHydrostaticRatioEnum);
+					GetInputListOnVertices(&bed[0],BedEnum);
+					GetInputListOnVertices(&surface[0],SurfaceEnum);
+
+					/*build new bed and surface: */
+					if (this->IsFloating()){
+						/*hydrostatic equilibrium: */
+						IssmDouble rho_ice,rho_water,di;
+						rho_ice   = this->matpar->GetRhoIce();
+						rho_water = this->matpar->GetRhoWater();
+						di        = rho_ice/rho_water;
+
+						/*build new thickness: */
+						for (j=0; j<3; j++) {
+							/*  for observed/interpolated/hydrostatic thickness, remove scaling from any hydrostatic thickness  */
+							if (hydrostatic_ratio[j] >= 0.)
+								thickness[j]=values[j]-(values[j]/thickness_init[j]-1.)*hydrostatic_ratio[j]*surface[j]/(1.-di);
+							/*  for minimum thickness, don't scale  */
+							else
+								thickness[j]=thickness_init[j];
+
+							/*  check the computed thickness and update bed*/
+							if (thickness[j] < 0.) thickness[j]=1./(1.-di);
+							bed[j]=surface[j]-thickness[j];
+						}
+					}
+					else{
+						/*build new thickness: */
+						for (j=0; j<3; j++) {
+							/*  for observed thickness, use scaled value  */
+							if (hydrostatic_ratio[j] >= 0.)
+								thickness[j]=values[j];
+							/*  for minimum thickness, don't scale  */
+							else
+								thickness[j]=thickness_init[j];
+						}
+
+						/*update bed on grounded ice: */
+						for(j=0;j<3;j++)bed[j]=surface[j]-thickness[j];
+					}
+
+					/*Add new inputs: */
+					this->inputs->AddInput(new TriaInput(ThicknessEnum,thickness,P1Enum));
+					this->inputs->AddInput(new TriaInput(BedEnum,bed,P1Enum));
+					this->inputs->AddInput(new TriaInput(SurfaceEnum,surface,P1Enum));
+
+					break;
+				default:
+					this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+			}
+			break;
+
+		default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+/*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;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*Create transient input: */
+
+			parameters->FindParam(&yts,ConstantsYtsEnum);
+			for(t=0;t<ncols;t++){ //ncols is the number of times
+
+				/*create input values: */
+				for(i=0;i<3;i++){
+					row=this->vertices[i]->Sid();
+					values[i]=(IssmDouble)matrix[ncols*row+t];
+				}
+
+				/*time? :*/
+				time=(IssmDouble)matrix[(nrows-1)*ncols+t]*yts;
+
+				if(t==0) transientinput=new TransientInput(name);
+				transientinput->AddTimeInput(new TriaInput(name,values,P1Enum),time);
+				transientinput->Configure(parameters);
+			}
+			this->inputs->AddInput(transientinput);
+			break;
+
+		default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_BALANCED_
+/*FUNCTION Tria::CreateKMatrixBalancethickness {{{*/
+ElementMatrix* Tria::CreateKMatrixBalancethickness(void){
+
+	switch(GetElementType()){
+		case P1Enum:
+			return CreateKMatrixBalancethickness_CG();
+		case P1DGEnum:
+			return CreateKMatrixBalancethickness_DG();
+		default:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixBalancethickness_CG {{{*/
+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 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);
+
+	/*Retrieve all Inputs and parameters: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&stabilization,BalancethicknessStabilizationEnum);
+	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(dim==2){
+		vxaverage_input=inputs->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		vxaverage_input=inputs->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+	}
+	h=sqrt(2*this->GetArea());
+
+	/*Start looping on the number of gaussian points:*/
+	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);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		vxaverage_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		vyaverage_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+
+		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,
+					&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);
+
+		if(stabilization==1){
+			/*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;
+		}
+		else if(stabilization==2){
+			/*MacAyeal*/
+			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);
+		}
+		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,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixBalancethickness_DG {{{*/
+ElementMatrix* Tria::CreateKMatrixBalancethickness_DG(void){
+
+	/*Constants*/
+	const int  numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries*/
+	int        i,j,dim;
+	IssmDouble vx,vy,Jdettria;
+	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);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Start looping on the number of gaussian points:*/
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		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);
+
+		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,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorBalancethickness{{{*/
+ElementVector* Tria::CreatePVectorBalancethickness(void){
+
+	switch(GetElementType()){
+		case P1Enum:
+			return CreatePVectorBalancethickness_CG();
+			break;
+		case P1DGEnum:
+			return CreatePVectorBalancethickness_DG();
+		default:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorBalancethickness_CG{{{*/
+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);
+
+	/*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);
+
+	/* Start  looping on the number of gaussian points: */
+	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);
+		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];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorBalancethickness_DG {{{*/
+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);
+
+	/*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);
+
+	/* Start  looping on the number of gaussian points: */
+	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);
+		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];
+	}
+
+	/*Clean up and return*/
+	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];
+
+	/*Recover info at the vertices: */
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&gl_melting_rate,GroundinglineMeltingRateEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	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;
+
+	/*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));
+			}
+		}
+		/*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{
+			bed_hydro=-density*h[i];
+			if (bed_hydro>ba[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));
+				}
+				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) _error_("Error: migration should be Aggressive, Soft or Subelement");
+				}
+			}
+		}
+	}
+
+	/*SubelementMigrationEnum: if one grounded, all grounded*/
+	if(migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
+		for(i=0;i<NUMVERTICES;i++){
+			if(nodes[i]->IsGrounded()){
+				groundedelement=true;
+				break;
+			}
+		}
+		floatingelement=!groundedelement;
+	}
+	else{
+		/*Otherwise: if one floating, all floating*/
+		for(i=0;i<NUMVERTICES;i++){
+			if(nodes[i]->IsFloating()){
+				floatingelement=true;
+				break;
+			}
+		}
+	}
+
+   /*Add basal melting rate if element just ungrounded*/
+	if(!this->IsFloating() && floatingelement==true){
+		for(i=0;i<NUMVERTICES;i++)melting[i]=gl_melting_rate/yts;
+		this->inputs->AddInput(new TriaInput(BasalforcingsMeltingRateEnum,&melting[0],P1Enum));
+	} 
+
+	/*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));
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::PotentialUngrounding{{{*/
+void  Tria::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){
+
+	int     i;
+	IssmDouble  h[NUMVERTICES],ba[NUMVERTICES];
+	IssmDouble  bed_hydro;
+	IssmDouble  rho_water,rho_ice,density;
+
+	/*material parameters: */
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	density=rho_ice/rho_water;
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&ba[0],BathymetryEnum);
+
+	/*go through vertices, and figure out which ones are grounded and want to unground: */
+	for(i=0;i<NUMVERTICES;i++){
+		/*Find if grounded vertices want to start floating*/
+		if (!nodes[i]->IsFloating()){
+			bed_hydro=-density*h[i];
+			if (bed_hydro>ba[i]){
+				/*Vertex that could potentially unground, flag it*/
+				potential_ungrounding->SetValue(nodes[i]->Sid(),1,INS_VAL);
+			}
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::UpdatePotentialUngrounding{{{*/
+int Tria::UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){
+
+	int i;
+	int nflipped=0;
+
+	/*Go through nodes, and whoever is on the potential_ungrounding, ends up in nodes_on_iceshelf: */
+	for(i=0;i<3;i++){
+		if (reCast<bool>(vertices_potentially_ungrounding[nodes[i]->Sid()])){
+			vec_nodes_on_iceshelf->SetValue(nodes[i]->Sid(),1,INS_VAL);
+
+			/*If node was not on ice shelf, we flipped*/
+			if(nodes_on_iceshelf[nodes[i]->Sid()]==0){
+				nflipped++;
+			}
+		}
+	}
+	return nflipped;
+}
+/*}}}*/
+#endif
Index: /issm/trunk/src/c/classes/Elements/Tria.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tria.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/Tria.h	(revision 15396)
@@ -0,0 +1,271 @@
+/*! \file Tria.h 
+ *  \brief: header file for tria object
+ */
+
+#ifndef _TRIA_H_
+#define _TRIA_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Element.h"
+#include "./ElementHook.h"
+#include "./TriaRef.h"
+class Parameters;
+class Inputs;
+class IoModel;
+class Results;
+class Node;
+class Material;
+class Matpar;
+class ElementMatrix;
+class ElementVector;
+class Vertex;
+
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/Enum/Enum.h"
+/*}}}*/
+
+class Tria: public Element,public ElementHook,public TriaRef{
+
+	public:
+
+		int          id;
+		int          sid;
+
+		Node       **nodes;                       // nodes
+		Vertex     **vertices;                    // 3 vertices
+		Material    *material;                    // 1 material ice
+		Matpar      *matpar;                      // 1 material parameter
+		int          horizontalneighborsids[3];
+
+		Parameters  *parameters;                  //pointer to solution parameters
+		Inputs      *inputs;
+		Results     *results;
+
+		/*Tria constructors, destructors {{{*/
+		Tria();
+		Tria(int tria_id,int tria_sid,int i, IoModel* iomodel,int nummodels);
+		~Tria();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		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
+		void  InputUpdateFromConstant(IssmDouble constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		/*}}}*/
+		/*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);
+
+		#ifdef _HAVE_RESPONSES_
+		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);
+		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);
+		#endif
+
+		#ifdef _HAVE_GIA_
+		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y);
+		#endif
+
+		#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);
+		IssmDouble RheologyBbarAbsGradient(int weight_index);
+		IssmDouble ThicknessAbsMisfit(     int weight_index);
+		IssmDouble SurfaceAbsVelMisfit(    int weight_index);
+		IssmDouble ThicknessAbsGradient(   int weight_index);
+		IssmDouble ThicknessAlongGradient( int weight_index);
+		IssmDouble ThicknessAcrossGradient(int weight_index);
+		IssmDouble BalancethicknessMisfit(     int weight_index);
+		IssmDouble SurfaceRelVelMisfit(    int weight_index);
+		IssmDouble SurfaceLogVelMisfit(    int weight_index);
+		IssmDouble SurfaceLogVxVyMisfit(   int weight_index);
+		IssmDouble SurfaceAverageVelMisfit(int weight_index);
+		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);
+		int    UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
+		#endif
+
+		/*}}}*/
+		/*Tria specific routines:{{{*/
+		ElementMatrix* CreateKMatrixBalancethickness(void);
+		ElementMatrix* CreateKMatrixBalancethickness_DG(void);
+		ElementMatrix* CreateKMatrixBalancethickness_CG(void);
+		ElementMatrix* CreateKMatrixMelting(void);
+		ElementMatrix* CreateKMatrixPrognostic(void);
+		ElementMatrix* CreateKMatrixPrognostic_CG(void);
+		ElementMatrix* CreateKMatrixPrognostic_DG(void);
+		ElementMatrix* CreateMassMatrix(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		ElementVector* CreatePVectorBalancethickness_DG(void);
+		ElementVector* CreatePVectorBalancethickness_CG(void);
+		ElementVector* CreatePVectorPrognostic(void);
+		ElementVector* CreatePVectorPrognostic_CG(void);
+		ElementVector* CreatePVectorPrognostic_DG(void);
+		ElementVector* CreatePVectorSlope(void);
+		IssmDouble     GetArea(void);
+		int            GetElementType(void);
+		void	         GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	         GetVertexPidList(int* doflist);
+		void           GetVertexSidList(int* sidlist);
+		void           GetConnectivityList(int* connectivity);
+		IssmDouble     GetGroundedPortion(IssmDouble* xyz_list);
+		void           GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating);
+		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype);
+		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
+		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue,int index); //TO BE REMOVED
+		void           GetInputListOnNodes(IssmDouble* pvalue,int enumtype);
+		void           GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
+		void           GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
+		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);
+		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);
+		#endif
+
+		#ifdef _HAVE_CONTROL_
+		ElementMatrix* CreateKMatrixAdjointBalancethickness(void);
+		ElementMatrix* CreateKMatrixAdjointMacAyeal(void);
+		ElementVector* CreatePVectorAdjointHoriz(void);
+		ElementVector* CreatePVectorAdjointStokes(void);
+		ElementVector* CreatePVectorAdjointBalancethickness(void);
+		void	  InputUpdateFromSolutionAdjointBalancethickness( IssmDouble* solution);
+		void	  InputUpdateFromSolutionAdjointHoriz( IssmDouble* solution);
+		#endif
+
+		#ifdef _HAVE_HYDROLOGY_
+		ElementMatrix* CreateKMatrixHydrologyShreve(void);
+		ElementMatrix* CreateKMatrixHydrologyDCInefficient(void);
+		ElementMatrix* CreateKMatrixHydrologyDCEfficient(void);
+		ElementVector* CreatePVectorHydrologyShreve(void);
+		ElementVector* CreatePVectorHydrologyDCInefficient(void);
+		ElementVector* CreatePVectorHydrologyDCEfficient(void);
+		void    GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type);
+		void    CreateHydrologyWaterVelocityInput(void);
+		void	  InputUpdateFromSolutionHydrology(IssmDouble* solution);
+		void	  InputUpdateFromSolutionHydrologyShreve(IssmDouble* solution);
+		void    InputUpdateFromSolutionHydrologyDC(IssmDouble* solution);
+		void	  InputUpdateFromSolutionHydrologyDCInefficient(IssmDouble* solution);
+		void	  InputUpdateFromSolutionHydrologyDCEfficient(IssmDouble* solution);
+		void    GetHydrologyDCInefficientHmax(IssmDouble* ph_max, Node* innode);
+		void    GetHydrologyTransfer(Vector<IssmDouble>* transfer);
+		void    HydrologyEPLGetActive(Vector<IssmDouble>* active_vec);
+		void    HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask);
+		bool    AllActive(void);
+		bool    AnyActive(void);
+		#endif
+		#ifdef _HAVE_BALANCED_
+		#endif
+
+		/*}}}*/
+
+};
+#endif  /* _TRIA_H */
Index: /issm/trunk/src/c/classes/Elements/TriaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/TriaRef.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/TriaRef.cpp	(revision 15396)
@@ -0,0 +1,630 @@
+/*!\file TriaRef.c
+ * \brief: implementation of the TriaRef 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"
+/*}}}*/
+
+/*Element macros*/
+#define NUMNODESP1 3
+#define NUMNODESP2 6
+
+/*Object constructors and destructor*/
+/*FUNCTION TriaRef::TriaRef(){{{*/
+TriaRef::TriaRef(){
+	this->element_type_list=NULL;
+}
+/*}}}*/
+/*FUNCTION TriaRef::TriaRef(int* types,int nummodels){{{*/
+TriaRef::TriaRef(const int nummodels){
+
+	/*Only allocate pointer*/
+	element_type_list=xNew<int>(nummodels);
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::~TriaRef(){{{*/
+TriaRef::~TriaRef(){
+	xDelete<int>(element_type_list);
+}
+/*}}}*/
+
+/*Management*/
+/*FUNCTION TriaRef::SetElementType{{{*/
+void TriaRef::SetElementType(int type,int type_counter){
+
+	_assert_(type==P1Enum || type==P1DGEnum);
+
+	/*initialize element type*/
+	this->element_type_list[type_counter]=type;
+}
+/*}}}*/
+
+/*Reference Element numerics*/
+/*FUNCTION TriaRef::GetBHydro {{{*/
+void TriaRef::GetBHydro(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
+	 * by: 
+	 *       Bi=[ dN/dx ]
+	 *          [ dN/dy ]
+	 * where N is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i]=dbasis[0*numnodes+i]; 
+		B[numnodes*1+i]=dbasis[1*numnodes+i]; 
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBMacAyeal {{{*/
+void TriaRef::GetBMacAyeal(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
+	 * by: 
+	 *       Bi=[ dN/dx           0    ]
+	 *          [   0           dN/dy  ]
+	 *          [ 1/2*dN/dy  1/2*dN/dx ]
+	 * where N is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*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]; 
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBMacAyealStokes {{{*/
+void TriaRef::GetBMacAyealStokes(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
+	 * by: 
+	 *       Bi=[   dN/dx         0     ]
+	 *          [       0       dN/dy   ]
+	 *          [  1/2*dN/dy  1/2*dN/dx ]
+	 * where N is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*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]; 
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetSegmentBFlux{{{*/
+void TriaRef::GetSegmentBFlux(IssmDouble* B,GaussTria* gauss, int index1,int index2){
+	/*Compute B  matrix. B=[phi1 phi2 -phi3 -phi4]
+	 *
+	 * and phi1=phi3 phi2=phi4
+	 *
+	 * We assume B has been allocated already, of size: 1x4
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis,gauss);
+
+	/*Build B for this segment*/
+	B[0] = +basis[index1];
+	B[1] = +basis[index2];
+	B[2] = -basis[index1];
+	B[3] = -basis[index2];
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetSegmentBprimeFlux{{{*/
+void TriaRef::GetSegmentBprimeFlux(IssmDouble* Bprime,GaussTria* gauss, int index1,int index2){
+	/*Compute Bprime  matrix. Bprime=[phi1 phi2 phi3 phi4]
+	 *
+	 * and phi1=phi3 phi2=phi4
+	 *
+	 * We assume Bprime has been allocated already, of size: 1x4
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis,gauss);
+
+	/*Build B'*/
+	Bprime[0] = basis[index1];
+	Bprime[1] = basis[index2];
+	Bprime[2] = basis[index1];
+	Bprime[3] = basis[index2];
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBPrognostic{{{*/
+void TriaRef::GetBPrognostic(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
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the interpolation function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for (int i=0;i<numnodes;i++){
+		B[numnodes*0+i]=basis[i];
+		B[numnodes*1+i]=basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBprimeMacAyeal {{{*/
+void TriaRef::GetBprimeMacAyeal(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
+	 * by: 
+	 *       Bi_prime=[ 2*dN/dx    dN/dy ]
+	 *                [   dN/dx  2*dN/dy ]
+	 *                [   dN/dy    dN/dx ]
+	 * where hNis the interpolation function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	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];
+		Bprime[NDOF2*numnodes*1+NDOF2*i+0] =    dbasis[0*numnodes+i];
+		Bprime[NDOF2*numnodes*1+NDOF2*i+1] = 2.*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];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBprimeMacAyealStokes {{{*/
+void TriaRef::GetBprimeMacAyealStokes(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
+	 * by: 
+	 *       Bprimei=[  dN/dx    0   ]
+	 *               [    0    dN/dy ]
+	 *               [  dN/dy  dN/dx ]
+	 N               [  dN/dx  dN/dy ]
+	 * where N is the interpolation function for node i.
+	 *
+	 * We assume Bprime has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*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]; 
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBprimePrognostic{{{*/
+void TriaRef::GetBprimePrognostic(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
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the interpolation function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		Bprime[numnodes*0+i]=dbasis[0*numnodes+i]; 
+		Bprime[numnodes*1+i]=dbasis[1*numnodes+i]; 
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBMacAyealFriction{{{*/
+void TriaRef::GetBMacAyealFriction(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
+	 * by: 
+	 *                 Bi=[ N   0 ]
+	 *                    [ 0   N ]
+	 * where N is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 2 x (numdof*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis,gauss);
+
+	/*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];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetJacobian{{{*/
+void TriaRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussTria* gauss){
+	/*The Jacobian is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1 = xyz_list[3*0+0];
+	IssmDouble y1 = xyz_list[3*0+1];
+	IssmDouble x2 = xyz_list[3*1+0];
+	IssmDouble y2 = xyz_list[3*1+1];
+	IssmDouble x3 = xyz_list[3*2+0];
+	IssmDouble y3 = xyz_list[3*2+1];
+
+	J[2*0+0] = 0.5*(x2-x1);
+	J[2*1+0] = SQRT3/6.0*(2*x3-x1-x2);
+	J[2*0+1] = 0.5*(y2-y1);
+	J[2*1+1] = SQRT3/6.0*(2*y3-y1-y2);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetSegmentJacobianDeterminant{{{*/
+void TriaRef::GetSegmentJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,GaussTria* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated*/
+
+	IssmDouble x1 = xyz_list[3*0+0];
+	IssmDouble y1 = xyz_list[3*0+1];
+	IssmDouble x2 = xyz_list[3*1+0];
+	IssmDouble y2 = xyz_list[3*1+1];
+
+	*Jdet = .5*sqrt(pow(x2-x1,2) + pow(y2-y1,2));
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetJacobianDeterminant{{{*/
+void TriaRef::GetJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,GaussTria* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+	IssmDouble J[2][2];
+
+	/*Get Jacobian*/
+	GetJacobian(&J[0][0],xyz_list,gauss);
+
+	/*Get Determinant*/
+	Matrix2x2Determinant(Jdet,&J[0][0]);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetJacobianInvert{{{*/
+void TriaRef::GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,GaussTria* gauss){
+
+	/*Jacobian*/
+	IssmDouble J[2][2];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0], xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	Matrix2x2Invert(Jinv,&J[0][0]);
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctions{{{*/
+void TriaRef::GetNodalFunctions(IssmDouble* basis,GaussTria* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(basis);
+
+	switch(this->element_type){
+		case P1Enum:
+		case P1DGEnum:
+			basis[0]=gauss->coord1;
+			basis[1]=gauss->coord2;
+			basis[2]=gauss->coord3;
+			return;
+		case P2Enum:
+			basis[0]=gauss->coord1*(2.*gauss->coord1-1.);
+			basis[1]=gauss->coord2*(2.*gauss->coord2-1.);
+			basis[2]=gauss->coord3*(2.*gauss->coord3-1.);
+			basis[3]=4.*gauss->coord3*gauss->coord2;
+			basis[4]=4.*gauss->coord3*gauss->coord1;
+			basis[5]=4.*gauss->coord1*gauss->coord2;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetSegmentNodalFunctions{{{*/
+void TriaRef::GetSegmentNodalFunctions(IssmDouble* basis,GaussTria* gauss,int index1,int index2){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(index1>=0 && index1<3);
+	_assert_(index2>=0 && index2<3);
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* triabasis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(triabasis,gauss);
+
+	switch(this->element_type){
+		case P1Enum:
+		case P1DGEnum:
+			basis[0]=triabasis[index1];
+			basis[1]=triabasis[index2];
+			xDelete<IssmDouble>(triabasis);
+			return;
+		case P2Enum:
+			_assert_(index2<index1);
+			basis[0]=triabasis[index1];
+			basis[1]=triabasis[index2];
+			basis[2]=triabasis[3+index2-1];
+			xDelete<IssmDouble>(triabasis);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(triabasis);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivatives{{{*/
+void TriaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTria* gauss){
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * actual coordinate system): */
+	IssmDouble    Jinv[2][2];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives in reference triangle*/
+	IssmDouble* dbasis_ref=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivativesReference(dbasis_ref,gauss); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dbasis: 
+	 * [dhi/dx]= Jinv*[dhi/dr]
+	 * [dhi/dy]       [dhi/ds]
+	 */
+	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];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(dbasis_ref);
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivativesReference{{{*/
+void TriaRef::GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTria* gauss){
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+
+	_assert_(dbasis && gauss);
+
+	switch(this->element_type){
+		case P1Enum: case P1DGEnum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP1*0+0]=-0.5; 
+			dbasis[NUMNODESP1*1+0]=-1.0/(2.0*SQRT3);
+			/*Nodal function 2*/
+			dbasis[NUMNODESP1*0+1]=0.5;
+			dbasis[NUMNODESP1*1+1]=-1.0/(2.0*SQRT3);
+			/*Nodal function 3*/
+			dbasis[NUMNODESP1*0+2]=0;
+			dbasis[NUMNODESP1*1+2]=1.0/SQRT3;
+			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.;
+			/*Nodal function 2*/
+			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.;
+			/*Nodal function 4*/
+			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;
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2*0+5]=2.*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2*1+5]=-2.*SQRT3/3.*(gauss->coord1+gauss->coord2);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetInputDerivativeValue{{{*/
+void TriaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTria* gauss){
+
+	/*From node values of parameter p (plist[0],plist[1],plist[2]), return parameter derivative value at gaussian 
+	 * point specified by gauss_basis:
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx+plist[2]*dh3/dx
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx+plist[2]*dh3/dx
+	 *
+	 * p is a vector already allocated.
+	 */
+
+	/*Output*/
+	IssmDouble dpx=0.;
+	IssmDouble dpy=0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpy += dbasis[1*numnodes+i]*plist[i];
+
+	/*Assign values*/
+	xDelete<IssmDouble>(dbasis);
+	*(p+0)=dpx;
+	*(p+1)=dpy;
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetInputValue{{{*/
+void TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussTria* gauss){
+
+	/*Output*/
+	IssmDouble value =0.;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis, gauss);
+
+	/*Calculate parameter for this Gauss point*/
+	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
+
+	/*Assign output pointer*/
+	xDelete<IssmDouble>(basis);
+	*p = value;
+}
+/*}}}*/
+/*FUNCTION TriaRef::NumberofNodes{{{*/
+int TriaRef::NumberofNodes(void){
+
+	switch(this->element_type){
+		case P1Enum:   return NUMNODESP1;
+		case P1DGEnum: return NUMNODESP1;
+		case P2Enum:   return NUMNODESP2;
+		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/TriaRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/TriaRef.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Elements/TriaRef.h	(revision 15396)
@@ -0,0 +1,48 @@
+/*!\file:  TriaRef.h
+ * \brief abstract class for handling Tria oriented routines, like nodal functions, 
+ * strain rate generation, etc ...
+ */ 
+
+#ifndef _TRIAREF_H_
+#define _TRIAREF_H_
+
+class GaussTria;
+
+class TriaRef{
+
+	public: 
+		int* element_type_list; //P1CG, P1DG, MINI, P2...
+		int  element_type;
+
+		TriaRef();
+		TriaRef(const int nummodels);
+		~TriaRef();
+
+		/*Management*/
+		void SetElementType(int type,int type_counter);
+
+		/*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 GetBHydro(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetBMacAyealFriction(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);
+		void GetJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,GaussTria* gauss);
+		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,GaussTria* gauss);
+		void GetNodalFunctions(IssmDouble* basis,GaussTria* gauss);
+		void GetSegmentNodalFunctions(IssmDouble* basis,GaussTria* gauss, int index1,int index2);
+		void GetSegmentBFlux(IssmDouble* B,GaussTria* gauss, int index1,int index2);
+		void GetSegmentBprimeFlux(IssmDouble* Bprime,GaussTria* gauss, int index1,int index2);
+		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTria* gauss);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTria* gauss);
+		void GetInputValue(IssmDouble* pp, IssmDouble* plist, GaussTria* gauss);
+		void GetInputDerivativeValue(IssmDouble* pp, IssmDouble* plist,IssmDouble* xyz_list, GaussTria* gauss);
+
+		int  NumberofNodes(void);
+};
+#endif
Index: /issm/trunk/src/c/classes/ExternalResults/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/classes/ExternalResults/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,5 @@
+# Subdirectories {{{
+# }}}
+# Include Directory {{{
+include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/ExternalResults)
+# }}}
Index: /issm/trunk/src/c/classes/ExternalResults/ExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/ExternalResult.h	(revision 15396)
+++ /issm/trunk/src/c/classes/ExternalResults/ExternalResult.h	(revision 15396)
@@ -0,0 +1,33 @@
+/*!\file:  ExternalResult.h
+ * \brief abstract class for ExternalResult object
+ */ 
+
+#ifndef _EXTERNALRESULT_H_
+#define _EXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../datastructures/datastructures.h"
+#include "../Node.h"
+/*}}}*/
+
+class ExternalResult: public Object{
+
+	public: 
+
+		virtual        ~ExternalResult(){};
+		/*Virtual functions:{{{*/
+		virtual int   InstanceEnum()=0;
+		virtual void  WriteData(FILE* fid,bool io_gather)=0;
+		virtual void  GetResultName(char**)=0;
+		virtual int   GetStep(void)=0;
+		/*}}}*/
+};
+#endif
Index: /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h	(revision 15396)
+++ /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h	(revision 15396)
@@ -0,0 +1,323 @@
+/*! \file GenericExternalResult.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _GENERIC_EXTERNAL_RESULT_
+#define _GENERIC_EXTERNAL_RESULT_
+
+/*Headers:{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+#include "./ExternalResult.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+template <class ResultType> 
+class GenericExternalResult: public ExternalResult {
+
+	private: 
+		int id;
+		int enum_type;
+		ResultType value;
+		int M;
+		int N;
+		int step;
+		IssmDouble time;
+
+	public:
+		/*Diverse: must be in front, as it is used in what follows*/
+		void GenericEcho(void){/*{{{*/
+			_printf_("   id: " << this->id << "\n");
+			_printf_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+			_printf_("   step: " << this->step << "\n");
+			_printf_("   time: " << this->time << "\n");
+		}
+		/*}}}*/
+		void GenericWriteData(FILE* fid){/*{{{*/ 
+
+			int     length;
+			IssmPDouble  passiveDouble;
+			char*   name = NULL;
+
+			/*First write enum: */
+			EnumToStringx(&name,this->enum_type);
+			length=(strlen(name)+1)*sizeof(char);
+			fwrite(&length,sizeof(int),1,fid);
+			fwrite(name,length,1,fid);
+			xDelete<char>(name);
+
+			/*Now write time and step: */
+			passiveDouble=reCast<IssmPDouble>(time);
+			fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
+			fwrite(&step,sizeof(int),1,fid);
+		} /*}}}*/
+
+		/*GenericExternalResult constructors and  destructors*/
+		GenericExternalResult(){ /*{{{*/
+			id  = 0;
+			enum_type = NoneEnum;
+			M=0;
+			N=0;
+			step=0;
+			time=0;
+		} /*}}}*/
+		GenericExternalResult(int in_id, int in_enum_type,ResultType in_values, int in_M,int in_N,int in_step,IssmDouble in_time){/*{{{*/
+			_error_("template GenericExternalResult(int in_id, int in_enum_type,double* in_values, int in_M,int in_N,int in_step,IssmDouble in_time) not implemented for this ResultType\n");
+		}
+/*}}}*/
+		GenericExternalResult(int in_id, int in_enum_type,ResultType in_value,int in_step, IssmDouble in_time){ /*{{{*/
+			id=in_id;
+			enum_type=in_enum_type;
+			value=in_value;
+			step=in_step;
+			time=in_time;
+		}
+		/*}}}*/
+		~GenericExternalResult(){ /*{{{*/
+		} /*}}}*/
+
+		/*Object virtual functions definitions:*/
+		void Echo(void){ /*{{{*/
+			this->DeepEcho();
+		}
+		/*}}}*/
+		void DeepEcho(void){ /*{{{*/
+			_error_("template DeepEcho not implemented for this ResultType\n");
+		}
+		/*}}}*/
+		int Id(void){ /*{{{*/ 
+			return -1; 
+		} /*}}}*/
+		int ObjectEnum(void){ /*{{{*/
+			_error_("template ObjectEnum not implemented for this ResultType\n");
+		} /*}}}*/
+		Object* copy(void) { /*{{{*/
+			return new GenericExternalResult<ResultType>(this->id,this->enum_type,this->value,this->step,this->time);
+		} /*}}}*/
+
+		/*GenericExternalResult management: */
+void WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	int     my_rank;
+	int     type;
+	int     size;
+	IssmPDouble  passiveDouble;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*use generic part, same for all ResultTypes: */
+	this->GenericWriteData(fid);
+
+	/*writing a IssmPDouble for Matlab or Python to post-process, type is 1, size is 1: */
+	type=1;
+	size=1;
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+
+	/*cast to a IssmPDouble: */
+	passiveDouble=reCast<IssmPDouble>(value);
+	fwrite(&passiveDouble,size*sizeof(IssmPDouble),1,fid);
+
+} /*}}}*/
+void GetResultName(char** pname){ /*{{{*/
+	EnumToStringx(pname,this->enum_type);
+} /*}}}*/
+int GetStep(void){ /*{{{*/
+	return this->step;
+} /*}}}*/
+int InstanceEnum(void){ /*{{{*/
+	return this->enum_type;
+} /*}}}*/
+};
+
+/*Specific instantiations for bool: */
+template <> inline void GenericExternalResult<bool>::DeepEcho(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<bool>:\n");
+	this->GenericEcho();
+	_printf_("   value: " <<(this->value?"true":"false") << "\n");
+
+} /*}}}*/
+template <> inline int GenericExternalResult<bool>::ObjectEnum(void){ /*{{{*/
+	return BoolExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for int: */
+template <> inline void GenericExternalResult<int>::DeepEcho(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<int>:\n");
+	this->GenericEcho();
+	_printf_("   value: " << this->value << "\n");
+
+} /*}}}*/
+template <> inline int GenericExternalResult<int>::ObjectEnum(void){ /*{{{*/
+	return IntExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for double: */
+template <> inline void GenericExternalResult<double>::DeepEcho(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<double>:\n");
+	this->GenericEcho();
+	_printf_("   value: " << this->value << "\n");
+
+} /*}}}*/
+template <> inline int GenericExternalResult<double>::ObjectEnum(void){ /*{{{*/
+	return DoubleExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for char*: */
+template <> inline GenericExternalResult<char*>::GenericExternalResult(int in_id, int in_enum_type,char* in_value,int in_step, IssmDouble in_time){ /*{{{*/
+
+	id=in_id;
+	enum_type=in_enum_type;
+	value=xNew<char>(strlen(in_value)+1);
+	xMemCpy<char>(value,in_value,(strlen(in_value)+1));
+	step=in_step;
+	time=in_time;
+
+} /*}}}*/
+template <> inline GenericExternalResult<char*>::~GenericExternalResult(){ /*{{{*/
+	xDelete<char>(value);
+} /*}}}*/
+template <> inline void GenericExternalResult<char*>::DeepEcho(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<char*>:\n");
+	this->GenericEcho();
+	_printf_("   value: " << this->value << "\n");
+
+} /*}}}*/
+template <> inline void GenericExternalResult<char*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	int     my_rank;
+	int     type;
+	int     length;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*use generic part, same for all ResultTypes: */
+	this->GenericWriteData(fid);
+
+	/*writing a string, type is 2: */
+	type=2;
+	fwrite(&type,sizeof(int),1,fid);
+
+	length=(strlen(this->value)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(this->value,length,1,fid);
+}
+/*}}}*/
+template <> inline int GenericExternalResult<char*>::ObjectEnum(void){ /*{{{*/
+	return StringExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for IssmPDouble*: */
+template <> inline GenericExternalResult<IssmPDouble*>::GenericExternalResult(int in_id, int in_enum_type,IssmPDouble* in_values, int in_M,int in_N,int in_step,IssmDouble in_time){/*{{{*/
+
+	id=in_id;
+	enum_type=in_enum_type;
+	M=in_M;
+	N=in_N;
+
+	step=in_step;
+	time=in_time;
+
+	/*Copy result in values*/
+	if(M*N){
+		value=xNew<IssmPDouble>(M*N);
+		xMemCpy<IssmPDouble>(value,in_values,M*N);
+	}
+	else value=NULL;
+}
+/*}}}*/
+template <> inline GenericExternalResult<IssmPDouble*>::GenericExternalResult(int in_id, int in_enum_type,IssmPDouble* in_value,int in_step, IssmDouble in_time){ /*{{{*/
+	_error_("you cannot initialize a GenericExternalResult<IssmPDouble*> without providing the dimensions of the matrix! Please use a more appropriate constructor!");
+} /*}}}*/
+template <> inline GenericExternalResult<IssmPDouble*>::~GenericExternalResult(){ /*{{{*/
+	xDelete<IssmPDouble>(value);
+} /*}}}*/
+template <> inline void GenericExternalResult<IssmPDouble*>::Echo(void){ /*{{{*/
+
+	_printf_("GenericExternalResult<IssmPDouble*>:\n");
+	this->GenericEcho();
+	_printf_("   matrix size: " << this->M << "-" << this->N << "\n");
+
+} /*}}}*/
+template <> inline void GenericExternalResult<IssmPDouble*>::DeepEcho(void){ /*{{{*/
+
+	int i,j;
+
+	_printf_("GenericExternalResult<IssmPDouble*>:\n");
+	this->GenericEcho();
+
+	_printf_("   matrix size: " << this->M << "-" << this->N << "\n");
+	for (i=0;i<this->M;i++){  
+		_printf_("   [ ");
+		for (j=0;j<this->N;j++){
+			_printf_( " " << setw(11) << setprecision (5) << this->value[i*this->N+j]);
+		}  
+		_printf_(" ]\n");
+	}  
+
+} /*}}}*/
+template <> inline Object* GenericExternalResult<IssmPDouble*>::copy(void){ /*{{{*/
+	return new GenericExternalResult<IssmPDouble*>(this->id,this->enum_type,this->value,this->M,this->N,this->step,this->time);
+} /*}}}*/
+template <> inline void GenericExternalResult<IssmPDouble*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	int     my_rank;
+	int     length;
+	int     type;
+	int     rows,cols;
+	char   *name    = NULL;
+	IssmPDouble passiveDouble;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(io_gather){
+		/*we are gathering the data on cpu 0, don't write on other cpus: */
+		if(my_rank) return;
+	}
+
+	/*First write enum: */
+	EnumToStringx(&name,this->enum_type);
+	length=(strlen(name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(name,length,1,fid);
+	xDelete<char>(name);
+
+	/*Now write time and step: */
+	passiveDouble=reCast<IssmPDouble>(time);
+	fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*writing a IssmDouble array, type is 3:*/
+	type=3;
+	fwrite(&type,sizeof(int),1,fid);
+	rows=this->M;
+	fwrite(&rows,sizeof(int),1,fid);
+	cols=this->N;
+	fwrite(&cols,sizeof(int),1,fid);
+	fwrite(value,cols*rows*sizeof(IssmPDouble),1,fid);
+
+}
+/*}}}*/
+template <> inline int GenericExternalResult<IssmPDouble*>::ObjectEnum(void){ /*{{{*/
+	return DoubleMatExternalResultEnum;
+} /*}}}*/
+
+#endif  /* _EXTERNAL_RESULTOBJECT_H */
Index: /issm/trunk/src/c/classes/ExternalResults/Results.cpp
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/Results.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/ExternalResults/Results.cpp	(revision 15396)
@@ -0,0 +1,81 @@
+/*
+ * \file Results.cpp
+ * \brief: Implementation of the Results class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Results.h"
+#include "./ExternalResult.h"
+#include "../../shared/shared.h"
+#include "../Params/Parameters.h"
+#include "../ElementResults/ElementResult.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Results::Results(){{{*/
+Results::Results(){
+	enum_type=ResultsEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Results::~Results(){{{*/
+Results::~Results(){
+	return;
+}
+/*}}}*/
+
+/*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){
+
+	int         i;
+	FILE       *fid          = NULL;
+	bool        io_gather=true;
+
+	/*Recover file descriptor: */
+	parameters->FindParam(&fid,OutputFilePointerEnum);
+	parameters->FindParam(&io_gather,SettingsIoGatherEnum);
+
+	for(i=0;i<this->Size();i++){
+		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
+
+		/*write result to disk: */
+		result->WriteData(fid,io_gather);
+	}
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/ExternalResults/Results.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/Results.h	(revision 15396)
+++ /issm/trunk/src/c/classes/ExternalResults/Results.h	(revision 15396)
@@ -0,0 +1,25 @@
+#ifndef _CONTAINER_RESULTS_H_
+#define  _CONTAINER_RESULTS_H_
+
+#include "../../datastructures/datastructures.h"
+
+/*forward declarations */
+class Parameters;
+
+/*!\brief Declaration of Results class.
+ *
+ * Declaration of Results class.  Results are vector lists (Containers) of Result objects.
+ */ 
+class Results: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Results();
+		~Results();
+
+		/*numerics*/
+		Results* SpawnTriaResults(int* indices);
+		void     Write(Parameters* parameters);
+};
+#endif //ifndef _RESULTS_H_
Index: /issm/trunk/src/c/classes/FemModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/FemModel.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/FemModel.cpp	(revision 15396)
@@ -1,3 +1,3 @@
-/*!\file FemModel.c
+/*!\file FemModel.cpp
  * \brief: implementation of the FemModel object
  */
@@ -10,15 +10,36 @@
 
 #include <stdio.h>
-#include "../Container/Container.h"
+#include "../analyses/analyses.h"
+#include "../shared/io/io.h"
+#include "./classes.h"
+#include "../shared/Enum/Enum.h"
+
+/*module includes: {{{*/
 #include "../modules/ModelProcessorx/ModelProcessorx.h"
-#include "../solutions/solutions.h"
-#include "../io/io.h"
-#include "./classes.h"
-#include "../include/include.h"
-#include "../EnumDefinitions/EnumDefinitions.h"
-#include "../modules/modules.h"
+#include "../modules/VerticesDofx/VerticesDofx.h"
+#include "../modules/SpcNodesx/SpcNodesx.h"
+#include "../modules/ConfigureObjectsx/ConfigureObjectsx.h"
+#include "../modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h"
+#include "../modules/OutputResultsx/OutputResultsx.h"
+#include "../modules/GetVectorFromInputsx/GetVectorFromInputsx.h"
+#include "../modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h"
+#include "../modules/NodesDofx/NodesDofx.h"
+#include "../modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h"
+#include "../modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h"
+#include "../modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h"
+#include "../modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h"
+#include "../modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h"
+#include "../modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h"
+#include "../modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h"
+#include "../modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h"
+#include "../modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h"
+#include "../modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
+#include "../modules/NodalValuex/NodalValuex.h"
+#include "../modules/GetVectorFromInputsx/GetVectorFromInputsx.h"
+#include "../modules/AverageOntoPartitionx/AverageOntoPartitionx.h"
+/*}}}*/
 
 /*Object constructors and destructor*/
-/*FUNCTION FemModel::FemModel(int argc,char** argv){{{*/
+/*FUNCTION FemModel::FemModel(int argc,char** argv,COMM incomm){{{*/
 FemModel::FemModel(int argc,char** argv,COMM incomm){
 
@@ -39,5 +60,5 @@
 	this->comm=incomm;
 	this->SetStaticComm();
-	
+
 	/*Now, initialize PETSC: */
 	#ifdef _HAVE_PETSC_
@@ -71,9 +92,9 @@
 }
 /*}}}*/
-/*FUNCTION FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){{{*/
-FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){
+/*FUNCTION FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){{{*/
+FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){
 
 	/*Call InitFromFiles. This constructor is just a wrapper: */
-	this->InitFromFiles(rootpath, inputfilename, outputfilename, petscfilename, lockfilename, in_solution_type,analyses,nummodels);
+	this->InitFromFiles(rootpath, inputfilename, outputfilename, toolkitsfilename, lockfilename, in_solution_type,analyses,nummodels);
 
 }
@@ -97,5 +118,5 @@
 	this->parameters->FindParam(&lockfilename,LockFileNameEnum);
 	if (waitonlock>0){
-		_pprintLine_("write lock file:");
+		_printf0_("write lock file:\n");
 		WriteLockFile(lockfilename);
 	}
@@ -116,21 +137,21 @@
 	/*Before we delete the profiler, report statistics for this run: */
 	profiler->Tag(Finish);  //final tagging
-	_pprintLine_("");
-	_pprintLine_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<profiler->DeltaTime(StartInit,FinishInit));
-	_pprintLine_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->DeltaTime(StartCore,FinishCore));
-	_pprintLine_("");
-	_pprintLine_("   Total elapsed time:"
+	_printf0_("\n");
+	_printf0_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<profiler->DeltaTime(StartInit,FinishInit) << "\n");
+	_printf0_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->DeltaTime(StartCore,FinishCore) << "\n");
+	_printf0_("\n");
+	_printf0_("   Total elapsed time:"
 			<<profiler->DeltaTimeModHour(Start,Finish)<<" hrs "
 			<<profiler->DeltaTimeModMin(Start,Finish)<<" min "
 			<<profiler->DeltaTimeModSec(Start,Finish)<<" sec"
 			);
-	_pprintLine_("");
+	_printf0_("\n");
 
 	/*Now delete: */
 	delete profiler;
-	
+
 	/*Finalize PETSC for this model: */
 	#ifdef _HAVE_PETSC_
-	_pprintLine_("closing Petsc");
+	_printf0_("closing Petsc\n");
 	PetscFinalize(); 
 	#endif
@@ -143,15 +164,15 @@
 void FemModel::Echo(void){
 
-	_printLine_("FemModel echo: ");
-	_printLine_("   number of fem models: " << nummodels);
-	_printLine_("   analysis_type_list: ");
-	for(int i=0;i<nummodels;i++)_printLine_("     " << i << ": " << EnumToStringx(analysis_type_list[i]));
-	_printLine_("   current analysis_type: ");
-	_printLine_("     " << analysis_counter << ": " << EnumToStringx(analysis_type_list[analysis_counter]));
-
-}
-/*}}}*/
-/*FUNCTION FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){{{*/
-void FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){
+	_printf_("FemModel echo: \n");
+	_printf_("   number of fem models: " << nummodels << "\n");
+	_printf_("   analysis_type_list: \n");
+	for(int i=0;i<nummodels;i++)_printf_("     " << i << ": " << EnumToStringx(analysis_type_list[i]) << "\n");
+	_printf_("   current analysis_type: \n");
+	_printf_("     " << analysis_counter << ": " << EnumToStringx(analysis_type_list[analysis_counter]) << "\n");
+
+}
+/*}}}*/
+/*FUNCTION FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){{{*/
+void FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){
 
 	/*intermediary*/
@@ -159,5 +180,5 @@
 	int         analysis_type;
 	FILE       *IOMODEL = NULL;
-	FILE       *petscoptionsfid = NULL;
+	FILE       *toolkitsoptionsfid = NULL;
 	FILE       *output_fid = NULL;
 	int         my_rank;
@@ -187,20 +208,20 @@
 	for(i=0;i<nummodels;i++){
 
-		if(VerboseMProcessor()) _pprintLine_("   Processing finite element model of analysis " << EnumToStringx(analysis_type_list[i]) << ":");
+		if(VerboseMProcessor()) _printf0_("   Processing finite element model of analysis " << EnumToStringx(analysis_type_list[i]) << ":\n");
 		analysis_type=analysis_type_list[i];
 		this->SetCurrentConfiguration(analysis_type);
 
 		if(i==0){
-			if(VerboseMProcessor()) _pprintLine_("      creating vertex degrees of freedom");
+			if(VerboseMProcessor()) _printf0_("      creating vertex PIDs\n");
 			VerticesDofx(vertices,parameters); //only call once, we only have one set of vertices
 		}
 
-		if(VerboseMProcessor()) _pprintLine_("      resolving node constraints");
+		if(VerboseMProcessor()) _printf0_("      resolving node constraints\n");
 		SpcNodesx(nodes,constraints,parameters,analysis_type); 
 
-		if(VerboseMProcessor()) _pprintLine_("      creating nodal degrees of freedom");
+		if(VerboseMProcessor()) _printf0_("      creating nodal degrees of freedom\n");
 		NodesDofx(nodes,parameters,analysis_type);
 
-		if(VerboseMProcessor()) _pprintLine_("      configuring element and loads");
+		if(VerboseMProcessor()) _printf0_("      configuring element and loads\n");
 		ConfigureObjectsx(elements, loads, nodes, vertices, materials,parameters);
 	}
@@ -217,8 +238,8 @@
 	this->parameters->AddObject(new StringParam(LockFileNameEnum,lockfilename));
 
-	/*Now, deal with petsc options, which need to be put into the parameters dataset: */
-	petscoptionsfid=pfopen(petscfilename,"r");
-	ParsePetscOptionsx(this->parameters,petscoptionsfid);
-	pfclose(petscoptionsfid,petscfilename);
+	/*Now, deal with toolkits options, which need to be put into the parameters dataset: */
+	toolkitsoptionsfid=pfopen(toolkitsfilename,"r");
+	ParseToolkitsOptionsx(this->parameters,toolkitsoptionsfid);
+	pfclose(toolkitsoptionsfid,toolkitsfilename);
 }
 /*}}}*/
@@ -226,5 +247,5 @@
 void FemModel::OutputResults(void){
 
-	_pprintLine_("write results to disk:");
+	_printf0_("write results to disk:\n");
 
 	/*Just call the OutputResultsx module: */
@@ -270,11 +291,9 @@
 	this->loads->SetCurrentConfiguration(elements, loads, nodes,vertices, materials,parameters);
 
-	#ifdef _HAVE_PETSC_
-	/*take care of petsc options, that depend on this analysis type (present only after model processor)*/
-	if(this->parameters->Exist(PetscOptionsStringsEnum)){
-		PetscOptionsFromAnalysis(this->parameters,analysis_type);
-		if(VerboseSolver()) _pprintLine_("      petsc Options set for analysis type: " << EnumToStringx(analysis_type));
-	}
-	#endif
+	/*take care of toolkits options, that depend on this analysis type (present only after model processor)*/
+	if(this->parameters->Exist(ToolkitsOptionsStringsEnum)){
+		ToolkitsOptionsFromAnalysis(this->parameters,analysis_type);
+		if(VerboseSolver()) _printf0_("      toolkits Options set for analysis type: " << EnumToStringx(analysis_type) << "\n");
+	}
 
 }
@@ -298,5 +317,5 @@
 	void (*solutioncore)(FemModel*)=NULL; //core solution function pointer
 
-	_pprintLine_("call computational core:");
+	_printf0_("call computational core:\n");
 
 	/*Retrieve solution_type from parameters: */
@@ -324,13 +343,26 @@
 		solution_memory=profiler->Memory(FinishCore);
 
-		_pprintLine_("Solution elapsed time  : " << solution_time << "  Seconds");
-		_pprintLine_("Solution elapsed flops : " << solution_flops << "  Flops");
-		_pprintLine_("Solution memory used   : " << solution_memory << "  Bytes");
-
+		_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");
+		
 		/*Add to results: */
 		results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingSolutionTimeEnum, solution_time, 1, 0));
 		results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingCurrentMemEnum, solution_memory, 1, 0));
 		results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingCurrentFlopsEnum, solution_flops, 1, 0));
-	}
+
+		#ifdef _HAVE_ADOLC_
+		solution_time=profiler->DeltaTime(StartAdCore,FinishAdCore);
+		solution_flops=profiler->DeltaFlops(StartAdCore,FinishAdCore);
+		solution_memory=profiler->Memory(FinishAdCore);
+
+		_printf0_("AD Solution elapsed time    : " << solution_time   << " Seconds\n");
+		_printf0_("AD Solution number of flops : " << solution_flops  << " Flops\n");
+		_printf0_("AD Solution memory used     : " << solution_memory << " Bytes\n");
+
+
+		#endif
+
+			}
 }
 /*}}}*/
@@ -638,10 +670,10 @@
 
 	/*Update element inputs*/
-	InputUpdateFromVectorx(elements,nodes,vertices,loads,materials,parameters,vz,VzMeshEnum,VertexEnum);
+	InputUpdateFromVectorx(elements,nodes,vertices,loads,materials,parameters,vz,VzMeshEnum,VertexPIdEnum);
 
 	/*Free ressources:*/
 	xDelete<IssmDouble>(thickness);
 	xDelete<IssmDouble>(bed);
-	xdelete(&vz);
+	delete vz;
 	return 1;
 }
@@ -649,6 +681,7 @@
 void FemModel::UpdateConstraintsx(void){ /*{{{*/
 
+	Element   *element = NULL;
 	IssmDouble time;
-	int    analysis_type;
+	int        analysis_type;
 
 	/*retrieve parameters: */
@@ -657,7 +690,13 @@
 
 	/*start module: */
-	if(VerboseModule()) _pprintLine_("   Updating constraints for time: " << time);
-
-	/*First, update dof constraints in nodes, using constraints: */
+	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: */
 	SpcNodesx(nodes,constraints,parameters,analysis_type); 
 
@@ -667,46 +706,47 @@
 }
 /*}}}*/
-void FemModel::Responsex(IssmDouble* responses,const char* response_descriptor,bool process_units,int weight_index){/*{{{*/
+void FemModel::Responsex(IssmDouble* responses,const char* response_descriptor,int weight_index){/*{{{*/
 
 	int response_descriptor_enum=StringToEnumx(response_descriptor);
-	this->Responsex(responses, response_descriptor_enum, process_units, weight_index);
-
-}
-/*}}}*/
-void FemModel::Responsex(IssmDouble* responses,int response_descriptor_enum,bool process_units,int weight_index){/*{{{*/
-
+	this->Responsex(responses, response_descriptor_enum,weight_index);
+
+}
+/*}}}*/
+void FemModel::Responsex(IssmDouble* responses,int response_descriptor_enum,int weight_index){/*{{{*/
 
 	switch (response_descriptor_enum){
 
 		#ifdef _HAVE_RESPONSES_
-		case IceVolumeEnum:              this->IceVolumex(responses,process_units); break;
-		case MinVelEnum:                 this->MinVelx(responses,process_units); break;
-		case MaxVelEnum:                 this->MaxVelx(                  responses,process_units); break;
-		case MinVxEnum:                  this->MinVxx(responses,process_units); break;
-		case MaxVxEnum:                  this->MaxVxx(                   responses,process_units); break;
-		case MaxAbsVxEnum:               this->MaxAbsVxx(                responses,process_units); break;
-		case MinVyEnum:                  this->MinVyx(responses,process_units); break;
-		case MaxVyEnum:                  this->MaxVyx(                   responses,process_units); break;
-		case MaxAbsVyEnum:               this->MaxAbsVyx(                responses,process_units); break;
-		case MinVzEnum:                  this->MinVzx(responses,process_units); break;
-		case MaxVzEnum:                  this->MaxVzx(                   responses,process_units); break;
-		case MaxAbsVzEnum:               this->MaxAbsVzx(                responses,process_units); break;
-		case MassFluxEnum:               this->MassFluxx(         responses,process_units); break;
-		case SurfaceAbsVelMisfitEnum:    SurfaceAbsVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
-		case SurfaceRelVelMisfitEnum:    SurfaceRelVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
-		case SurfaceLogVelMisfitEnum:    SurfaceLogVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
-		case SurfaceLogVxVyMisfitEnum:   SurfaceLogVxVyMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
-		case SurfaceAverageVelMisfitEnum:SurfaceAverageVelMisfitx( responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
-		case ThicknessAbsMisfitEnum:     ThicknessAbsMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
-		case ThicknessAbsGradientEnum:   this->ThicknessAbsGradientx(responses, process_units,weight_index); break;
-		case ThicknessAlongGradientEnum: ThicknessAlongGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
-		case ThicknessAcrossGradientEnum:ThicknessAcrossGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
-		case BalancethicknessMisfitEnum:BalancethicknessMisfitx(responses,process_units,weight_index); break;
-		case TotalSmbEnum:					this->TotalSmbx(responses,process_units); break;
-		case RheologyBbarAbsGradientEnum:RheologyBbarAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
-		case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
-		case MaterialsRheologyBbarEnum: this->ElementResponsex(responses,MaterialsRheologyBbarEnum,process_units); break;
-		case VelEnum:                   this->ElementResponsex(responses,VelEnum,process_units); break;
-		case FrictionCoefficientEnum:NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case IceVolumeEnum:              this->IceVolumex(responses); break;
+		case MinVelEnum:                 this->MinVelx(responses); break;
+		case MaxVelEnum:                 this->MaxVelx(                  responses); break;
+		case MinVxEnum:                  this->MinVxx(responses); break;
+		case MaxVxEnum:                  this->MaxVxx(                   responses); break;
+		case MaxAbsVxEnum:               this->MaxAbsVxx(                responses); break;
+		case MinVyEnum:                  this->MinVyx(responses); break;
+		case MaxVyEnum:                  this->MaxVyx(                   responses); break;
+		case MaxAbsVyEnum:               this->MaxAbsVyx(                responses); break;
+		case MinVzEnum:                  this->MinVzx(responses); break;
+		case MaxVzEnum:                  this->MaxVzx(                   responses); break;
+		case MaxAbsVzEnum:               this->MaxAbsVzx(                responses); break;
+		case MassFluxEnum:               this->MassFluxx(         responses); break;
+		#ifdef _HAVE_CONTROL_
+		case SurfaceAbsVelMisfitEnum:    SurfaceAbsVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
+		case SurfaceRelVelMisfitEnum:    SurfaceRelVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
+		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 ThicknessAbsMisfitEnum:     ThicknessAbsMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
+		case ThicknessAbsGradientEnum:   this->ThicknessAbsGradientx(responses,weight_index); break;
+		case ThicknessAlongGradientEnum: ThicknessAlongGradientx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
+		case ThicknessAcrossGradientEnum:ThicknessAcrossGradientx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
+		case RheologyBbarAbsGradientEnum:RheologyBbarAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
+		case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
+		case BalancethicknessMisfitEnum:BalancethicknessMisfitx(responses,weight_index); break;
+		#endif
+		case TotalSmbEnum:					this->TotalSmbx(responses); break;
+		case MaterialsRheologyBbarEnum: this->ElementResponsex(responses,MaterialsRheologyBbarEnum); break;
+		case VelEnum:                   this->ElementResponsex(responses,VelEnum); break;
+		case FrictionCoefficientEnum:NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters); break;
 		default: _error_("response descriptor \"" << EnumToStringx(response_descriptor_enum) << "\" not supported yet!"); break;
 		#else
@@ -718,5 +758,4 @@
 /*}}}*/
 void FemModel::RequestedOutputsx(int* requested_outputs, int numoutputs){/*{{{*/
-
 
 	int      output_enum;
@@ -738,13 +777,13 @@
 
 				case IceVolumeEnum:
-					Responsex(&output_value,"IceVolume",false,0);
+					Responsex(&output_value,"IceVolume",0);
 					results->AddObject(new GenericExternalResult<double>(results->Size()+1,IceVolumeEnum,reCast<IssmPDouble>(output_value),step,time));
 					break;
 				case TotalSmbEnum:
-					Responsex(&output_value,"TotalSmb",false,0);
+					Responsex(&output_value,"TotalSmb",0);
 					results->AddObject(new GenericExternalResult<double>(results->Size()+1,TotalSmbEnum,reCast<IssmPDouble>(output_value),step,time));
 					break;
 				case MaxVelEnum:
-					Responsex(&output_value,"MaxVel",false,0);
+					Responsex(&output_value,"MaxVel",0);
 					results->AddObject(new GenericExternalResult<double>(results->Size()+1,MaxVelEnum,reCast<IssmPDouble>(output_value),step,time));
 					break;
@@ -763,5 +802,4 @@
 void FemModel::RequestedDependentsx(void){/*{{{*/
 
-
 	bool        isautodiff      = false;
 	IssmDouble  output_value;
@@ -811,5 +849,5 @@
 
 	/*Display message*/
-	if(VerboseModule()) _pprintLine_("   Generating matrices");
+	if(VerboseModule()) _printf0_("   Generating matrices\n");
 
 	/*retrive parameters: */
@@ -826,6 +864,7 @@
 		for (i=0;i<this->elements->Size();i++){
 			element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
-			element->CreateKMatrix(Kff_temp,NULL,NULL);
-		}
+			element->CreateKMatrix(Kff_temp,NULL);
+		}
+
 		for (i=0;i<this->loads->Size();i++){
 			load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
@@ -845,6 +884,7 @@
 	for (i=0;i<this->elements->Size();i++){
 		element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
-		element->CreateKMatrix(Kff,Kfs,df);
-	}
+		element->CreateKMatrix(Kff,Kfs);
+	}
+	
 	for (i=0;i<this->loads->Size();i++){
 		load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
@@ -872,4 +912,10 @@
 			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);
 	}
 
@@ -884,11 +930,11 @@
 	/*Assign output pointers: */
 	if(pKff) *pKff=Kff;
-	else      xdelete(&Kff);
+	else      delete Kff;
 	if(pKfs) *pKfs=Kfs;
-	else      xdelete(&Kfs);
+	else      delete Kfs;
 	if(ppf)  *ppf=pf;
-	else      xdelete(&pf);
+	else      delete pf;
 	if(pdf)  *pdf=df;
-	else      xdelete(&df);
+	else      delete df;
 	if(pkmax) *pkmax=kmax;
 }
@@ -927,5 +973,5 @@
 /*}}}*/
 #ifdef _HAVE_RESPONSES_
-void FemModel::MassFluxx(IssmDouble* pmass_flux,bool process_units){/*{{{*/
+void FemModel::MassFluxx(IssmDouble* pmass_flux){/*{{{*/
 
 	int          i,j;
@@ -963,5 +1009,5 @@
 			if (element->Id()==element_id){
 				/*We found the element which owns this segment, use it to compute the mass flux: */
-				mass_flux+=element->MassFlux(segments+5*i+0,process_units);
+				mass_flux+=element->MassFlux(segments+5*i+0);
 				break;
 			}
@@ -987,5 +1033,5 @@
 
 }/*}}}*/
-void FemModel::MaxAbsVxx(IssmDouble* pmaxabsvx,bool process_units){/*{{{*/
+void FemModel::MaxAbsVxx(IssmDouble* pmaxabsvx){/*{{{*/
 
 	int i;
@@ -998,5 +1044,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxAbsVx(&element_maxabsvx,process_units);
+		element->MaxAbsVx(&element_maxabsvx);
 		if(element_maxabsvx>maxabsvx) maxabsvx=element_maxabsvx;
 	}
@@ -1013,5 +1059,5 @@
 
 }/*}}}*/
-void FemModel::MaxAbsVyx(IssmDouble* pmaxabsvy,bool process_units){/*{{{*/
+void FemModel::MaxAbsVyx(IssmDouble* pmaxabsvy){/*{{{*/
 
 	int i;
@@ -1024,5 +1070,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxAbsVy(&element_maxabsvy,process_units);
+		element->MaxAbsVy(&element_maxabsvy);
 		if(element_maxabsvy>maxabsvy) maxabsvy=element_maxabsvy;
 	}
@@ -1039,5 +1085,5 @@
 
 }/*}}}*/
-void FemModel::MaxAbsVzx(IssmDouble* pmaxabsvz,bool process_units){/*{{{*/
+void FemModel::MaxAbsVzx(IssmDouble* pmaxabsvz){/*{{{*/
 
 	int i;
@@ -1050,5 +1096,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxAbsVz(&element_maxabsvz,process_units);
+		element->MaxAbsVz(&element_maxabsvz);
 		if(element_maxabsvz>maxabsvz) maxabsvz=element_maxabsvz;
 	}
@@ -1065,5 +1111,5 @@
 
 }/*}}}*/
-void FemModel::MaxVelx(IssmDouble* pmaxvel,bool process_units){/*{{{*/
+void FemModel::MaxVelx(IssmDouble* pmaxvel){/*{{{*/
 
 	int i;
@@ -1076,5 +1122,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxVel(&element_maxvel,process_units);
+		element->MaxVel(&element_maxvel);
 		if(element_maxvel>maxvel) maxvel=element_maxvel;
 	}
@@ -1091,5 +1137,5 @@
 
 }/*}}}*/
-void FemModel::MaxVxx(IssmDouble* pmaxvx,bool process_units){/*{{{*/
+void FemModel::MaxVxx(IssmDouble* pmaxvx){/*{{{*/
 
 	int i;
@@ -1102,5 +1148,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxVx(&element_maxvx,process_units);
+		element->MaxVx(&element_maxvx);
 		if(element_maxvx>maxvx) maxvx=element_maxvx;
 	}
@@ -1117,5 +1163,5 @@
 
 }/*}}}*/
-void FemModel::MaxVyx(IssmDouble* pmaxvy,bool process_units){/*{{{*/
+void FemModel::MaxVyx(IssmDouble* pmaxvy){/*{{{*/
 
 	int i;
@@ -1128,5 +1174,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxVy(&element_maxvy,process_units);
+		element->MaxVy(&element_maxvy);
 		if(element_maxvy>maxvy) maxvy=element_maxvy;
 	}
@@ -1143,5 +1189,5 @@
 
 }/*}}}*/
-void FemModel::MaxVzx(IssmDouble* pmaxvz,bool process_units){/*{{{*/
+void FemModel::MaxVzx(IssmDouble* pmaxvz){/*{{{*/
 
 	int i;
@@ -1154,5 +1200,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MaxVz(&element_maxvz,process_units);
+		element->MaxVz(&element_maxvz);
 		if(element_maxvz>maxvz) maxvz=element_maxvz;
 	}
@@ -1169,5 +1215,5 @@
 
 }/*}}}*/
-void FemModel::MinVelx(IssmDouble* pminvel,bool process_units){/*{{{*/
+void FemModel::MinVelx(IssmDouble* pminvel){/*{{{*/
 
 	int i;
@@ -1180,5 +1226,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MinVel(&element_minvel,process_units);
+		element->MinVel(&element_minvel);
 		if(element_minvel<minvel) minvel=element_minvel;
 	}
@@ -1195,5 +1241,5 @@
 
 }/*}}}*/
-void FemModel::MinVxx(IssmDouble* pminvx,bool process_units){/*{{{*/
+void FemModel::MinVxx(IssmDouble* pminvx){/*{{{*/
 
 	int i;
@@ -1206,5 +1252,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MinVx(&element_minvx,process_units);
+		element->MinVx(&element_minvx);
 		if(element_minvx<minvx) minvx=element_minvx;
 	}
@@ -1221,5 +1267,5 @@
 
 }/*}}}*/
-void FemModel::MinVyx(IssmDouble* pminvy,bool process_units){/*{{{*/
+void FemModel::MinVyx(IssmDouble* pminvy){/*{{{*/
 
 	int i;
@@ -1232,5 +1278,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MinVy(&element_minvy,process_units);
+		element->MinVy(&element_minvy);
 		if(element_minvy<minvy) minvy=element_minvy;
 	}
@@ -1247,5 +1293,5 @@
 
 }/*}}}*/
-void FemModel::MinVzx(IssmDouble* pminvz,bool process_units){/*{{{*/
+void FemModel::MinVzx(IssmDouble* pminvz){/*{{{*/
 
 	int i;
@@ -1258,5 +1304,5 @@
 	for(i=0;i<this->elements->Size();i++){
 		Element* element=(Element*)this->elements->GetObjectByOffset(i);
-		element->MinVz(&element_minvz,process_units);
+		element->MinVz(&element_minvz);
 		if(element_minvz<minvz) minvz=element_minvz;
 	}
@@ -1273,5 +1319,5 @@
 
 }/*}}}*/
-void FemModel::TotalSmbx(IssmDouble* pSmb,bool process_units){/*{{{*/
+void FemModel::TotalSmbx(IssmDouble* pSmb){/*{{{*/
 
 	IssmDouble local_smb = 0;
@@ -1293,5 +1339,5 @@
 
 }/*}}}*/
-void FemModel::IceVolumex(IssmDouble* pV,bool process_units){/*{{{*/
+void FemModel::IceVolumex(IssmDouble* pV){/*{{{*/
 
 	IssmDouble local_ice_volume = 0;
@@ -1313,5 +1359,5 @@
 
 }/*}}}*/
-void FemModel::ElementResponsex(IssmDouble* presponse,int response_enum,bool process_units){/*{{{*/
+void FemModel::ElementResponsex(IssmDouble* presponse,int response_enum){/*{{{*/
 
 	int found=0;
@@ -1344,5 +1390,5 @@
 	/*Ok, we found the element, compute responseocity: */
 	if(my_rank==cpu_found){
-		element->ElementResponse(&response,response_enum,IuToExtEnum);
+		element->ElementResponse(&response,response_enum);
 	}
 
@@ -1359,5 +1405,5 @@
 #endif
 #ifdef _HAVE_CONTROL_
-void FemModel::BalancethicknessMisfitx(IssmDouble* presponse,bool process_units,int weight_index){/*{{{*/
+void FemModel::BalancethicknessMisfitx(IssmDouble* presponse,int weight_index){/*{{{*/
 
 	IssmDouble J = 0;
@@ -1366,5 +1412,5 @@
 	for(int i=0;i<this->elements->Size();i++){
 		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
-		J+=element->BalancethicknessMisfit(process_units,weight_index);
+		J+=element->BalancethicknessMisfit(weight_index);
 	}
 	#ifdef _HAVE_MPI_
@@ -1378,6 +1424,5 @@
 
 }/*}}}*/
-void FemModel::ThicknessAbsGradientx( IssmDouble* pJ, bool process_units, int weight_index){/*{{{*/
-
+void FemModel::ThicknessAbsGradientx( IssmDouble* pJ, int weight_index){/*{{{*/
 
 	/*Intermediary*/
@@ -1392,5 +1437,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->ThicknessAbsGradient(process_units,weight_index);
+		J+=element->ThicknessAbsGradient(weight_index);
 	}
 
@@ -1408,5 +1453,4 @@
 void FemModel::CostFunctionx(IssmDouble* pJ){/*{{{*/
 
-
 	/*Intermediary*/
 	int      num_responses;
@@ -1424,5 +1468,5 @@
 	J=0;
 	for(int i=0;i<num_responses;i++){
-		this->Responsex(&Jplus,EnumToStringx(responses[i]),false,i); //False means DO NOT process units
+		this->Responsex(&Jplus,EnumToStringx(responses[i]),i);
 		J+=Jplus;
 	}
@@ -1437,8 +1481,6 @@
 void FemModel::DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses){/*{{{*/
 
-
 	int        i,j;
 	int        my_rank;
-	bool       process_units = true;
 
 	/*intermediary: */
@@ -1493,5 +1535,5 @@
 			parameters->SetParam(index,IndexEnum);
 
-			this->Responsex(&femmodel_response,root,process_units,0);//0 is the index for weights
+			this->Responsex(&femmodel_response,root,0);//0 is the index for weights
 
 			if(my_rank==0){
@@ -1512,5 +1554,5 @@
 
 			/*perfectly normal response function: */
-			this->Responsex(&femmodel_response,root,process_units,0);//0 is the weight index
+			this->Responsex(&femmodel_response,root,0);//0 is the weight index
 
 			if(my_rank==0){
@@ -1527,8 +1569,8 @@
 	/*Synthesize echo: {{{*/
 	if(my_rank==0){
-		_printString_("   responses: " << d_numresponses << ": ");
-		for(i=0;i<d_numresponses-1;i++)_printString_(d_responses[i] << "|");
-		_printString_(d_responses[d_numresponses-1]);
-		_printLine_("");
+		_printf_("   responses: " << d_numresponses << ": ");
+		for(i=0;i<d_numresponses-1;i++)_printf_(d_responses[i] << "|");
+		_printf_(d_responses[d_numresponses-1]);
+		_printf_("\n");
 	}
 	/*}}}*/
@@ -1537,2 +1579,104 @@
 /*}}}*/
 #endif
+#ifdef _HAVE_GIA_
+void FemModel::Deflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt, IssmDouble* x, IssmDouble* y){ /*{{{*/
+
+  int      i;
+
+	/*intermediary: */
+	Element *element     = NULL;
+
+	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
+	for (i=0;i<elements->Size();i++){
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->GiaDeflection(wg,dwgdt, x,y);
+	}
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_HYDROLOGY_
+void FemModel::HydrologyEPLupdateDomainx(void){ /*{{{*/
+
+	Vector<IssmDouble>* mask          = NULL;
+	IssmDouble*         serial_mask   = NULL;
+	Vector<IssmDouble>* active        = NULL;
+	IssmDouble*         serial_active = NULL;
+
+	/*Step 1: update maks, the mask might be extended by residual and/or using downstream sediment head*/
+	mask=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+	for (int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->HydrologyEPLGetMask(mask);
+	}
+
+	/*Assemble and serialize*/
+	mask->Assemble();
+	serial_mask=mask->ToMPISerial();
+	delete mask;
+
+	/*Update Mask*/
+	InputUpdateFromVectorx(elements,nodes,vertices,loads,materials,parameters,serial_mask,HydrologydcMaskEplactiveEnum,NodeSIdEnum);
+	xDelete<IssmDouble>(serial_mask);
+
+	/*Step 2: update node activity. If one element is connected to mask=1, all nodes are active*/
+	active=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+	for (int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->HydrologyEPLGetActive(active);
+	}
+
+	/*Assemble and serialize*/
+	active->Assemble();
+	serial_active=active->ToMPISerial();
+	delete active;
+
+	/*Update node activation accordingly*/
+	int counter =0;
+	for (int i=0;i<nodes->Size();i++){
+		Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
+		if(node->InAnalysis(HydrologyDCEfficientAnalysisEnum)){
+			if(serial_active[node->Sid()]==1.){
+				node->Activate();
+				counter++;
+			}
+			else{
+				node->Deactivate();
+			}
+		}
+	}
+	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());                
+	counter=sum_counter;
+	#endif
+	if(VerboseSolution()) _printf0_("   Number of active nodes in EPL layer: "<< counter <<"\n");
+
+	/*Update dof indexings*/
+	this->UpdateConstraintsx();
+
+}
+/*}}}*/
+void FemModel::HydrologyTransferx(void){ /*{{{*/
+
+	Vector<IssmDouble>* transferg=NULL; 
+
+	/*Vector allocation*/
+	transferg=new Vector<IssmDouble>(nodes->NumberOfNodes());
+
+	for (int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->GetHydrologyTransfer(transferg);
+	}
+	/*Assemble*/
+	transferg->Assemble();
+
+	/*Update Inputs*/
+	InputUpdateFromVectorx(elements,nodes,vertices,loads,materials,parameters,transferg,WaterTransferEnum,NodesEnum);
+
+	delete transferg;
+}
+/*}}}*/
+#endif
Index: /issm/trunk/src/c/classes/FemModel.h
===================================================================
--- /issm/trunk/src/c/classes/FemModel.h	(revision 15395)
+++ /issm/trunk/src/c/classes/FemModel.h	(revision 15396)
@@ -8,5 +8,4 @@
 /*Headers:*/
 /*{{{*/
-#include "./objects/Object.h"
 #include "../toolkits/toolkits.h"
 class DataSet;
@@ -65,20 +64,20 @@
 		/*Modules*/ 
 		#ifdef _HAVE_RESPONSES_
-		void MassFluxx(IssmDouble* presponse,bool process_units);
-		void MaxAbsVxx(IssmDouble* presponse,bool process_units);
-		void MaxAbsVyx(IssmDouble* presponse,bool process_units);
-		void MaxAbsVzx(IssmDouble* presponse,bool process_units);
-		void MaxVelx(IssmDouble* presponse,bool process_units);
-		void MaxVxx(IssmDouble* presponse,bool process_units);
-		void MaxVyx(IssmDouble* presponse,bool process_units);
-		void MaxVzx(IssmDouble* presponse,bool process_units);
-		void MinVelx(IssmDouble* presponse,bool process_units);
-		void MinVxx(IssmDouble* presponse,bool process_units);
-		void MinVyx(IssmDouble* presponse,bool process_units);
-		void MinVzx(IssmDouble* presponse,bool process_units);
-		void TotalSmbx(IssmDouble* pSmb,bool process_units);
-		void IceVolumex(IssmDouble* pV,bool process_units);
-		void ElementResponsex(IssmDouble* presponse,int response_enum,bool process_units);
-		void BalancethicknessMisfitx(IssmDouble* pV,bool process_units,int weight_index);
+		void MassFluxx(IssmDouble* presponse);
+		void MaxAbsVxx(IssmDouble* presponse);
+		void MaxAbsVyx(IssmDouble* presponse);
+		void MaxAbsVzx(IssmDouble* presponse);
+		void MaxVelx(IssmDouble* presponse);
+		void MaxVxx(IssmDouble* presponse);
+		void MaxVyx(IssmDouble* presponse);
+		void MaxVzx(IssmDouble* presponse);
+		void MinVelx(IssmDouble* presponse);
+		void MinVxx(IssmDouble* presponse);
+		void MinVyx(IssmDouble* presponse);
+		void MinVzx(IssmDouble* presponse);
+		void TotalSmbx(IssmDouble* pSmb);
+		void IceVolumex(IssmDouble* pV);
+		void ElementResponsex(IssmDouble* presponse,int response_enum);
+		void BalancethicknessMisfitx(IssmDouble* pV,int weight_index);
 		#endif
 		#ifdef  _HAVE_DAKOTA_
@@ -87,9 +86,12 @@
 		void RequestedOutputsx(int* requested_outputs, int numoutputs);
 		void RequestedDependentsx(void);
-		void Responsex(IssmDouble* presponse,int response_descriptor_enum,bool process_units,int weight_index);
-		void Responsex(IssmDouble* presponse,const char* response_descriptor,bool process_units,int weight_index);
+		void Responsex(IssmDouble* presponse,int response_descriptor_enum,int weight_index);
+		void Responsex(IssmDouble* presponse,const char* response_descriptor,int weight_index);
 		#ifdef _HAVE_CONTROL_
 		void CostFunctionx( IssmDouble* pJ);
-		void ThicknessAbsGradientx( IssmDouble* pJ, bool process_units,int weight_index);
+		void ThicknessAbsGradientx( IssmDouble* pJ,int weight_index);
+		#endif
+		#ifdef _HAVE_GIA_
+		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);
@@ -97,4 +99,7 @@
 		void UpdateConstraintsx(void);
 		int  UpdateVertexPositionsx(void);
+		void ParEplMask(void);		
+		void HydrologyTransferx(void);
+		void HydrologyEPLupdateDomainx(void);
 };
 
Index: /issm/trunk/src/c/classes/GiaDeflectionCoreArgs.h
===================================================================
--- /issm/trunk/src/c/classes/GiaDeflectionCoreArgs.h	(revision 15396)
+++ /issm/trunk/src/c/classes/GiaDeflectionCoreArgs.h	(revision 15396)
@@ -0,0 +1,40 @@
+/*!\file:  GiaDeflectionCoreArgs.h
+ * \brief place holder for arguments to the GiaDeflectionCoreArgs routine
+ */ 
+
+#ifndef _GIADEFLECTIONCOREARGS_H_
+#define _GIADEFLECTIONCOREARGS_H_
+
+struct GiaDeflectionCoreArgs{
+
+	/*inputs: */
+	IssmDouble ri; //radial distance from center of disk to vertex  i
+	IssmDouble re; //radius of disk
+	IssmDouble* hes; //loading history (in ice thickness)
+	IssmDouble* times; //loading history times
+	int numtimes; //loading history length
+	IssmDouble currenttime; 
+
+	/*gia material parameters: */
+	IssmDouble lithosphere_shear_modulus;
+	IssmDouble lithosphere_density;
+	IssmDouble mantle_shear_modulus;
+	IssmDouble mantle_viscosity;
+	IssmDouble mantle_density;
+	IssmDouble lithosphere_thickness;
+
+	/*gia solution parameters: */
+	int iedge;
+
+	/*ice properties: */
+	IssmDouble rho_ice;
+
+	/*constants: */
+	IssmDouble yts;
+
+	/*debug info: */
+	int        idisk; //id of the element we are running the gia code in.
+
+};
+
+#endif
Index: /issm/trunk/src/c/classes/Hook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Hook.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/Hook.cpp	(revision 15396)
@@ -12,8 +12,6 @@
 #include <string.h>
 #include "./classes.h"
-#include "../Container/Container.h"
-#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/Enum/Enum.h"
 #include "../shared/shared.h"
-#include "../include/include.h"
 
 /*Constructor/Destructors*/
@@ -68,15 +66,15 @@
 	int i;
 	if (num){
-		_printLine_("   Hook: ");
-		_printLine_("      num=" << this->num);
-		_printString_("      ids: ");
-		for (i=0;i<this->num;i++) _printString_(this->ids[i] << " ");
-		_printLine_("");
-		_printString_("      offsets: ");
-		for (i=0;i<this->num;i++) _printString_(this->offsets[i] << " ");
-		_printLine_("");
+		_printf_("   Hook: \n");
+		_printf_("      num=" << this->num << "\n");
+		_printf_("      ids: ");
+		for (i=0;i<this->num;i++) _printf_(this->ids[i] << " ");
+		_printf_("\n");
+		_printf_("      offsets: ");
+		for (i=0;i<this->num;i++) _printf_(this->offsets[i] << " ");
+		_printf_("\n");
 	}
 	else{
-		_printLine_("   Hook: num=0 ");
+		_printf_("   Hook: num=0 \n");
 	}
 }
@@ -87,24 +85,24 @@
 	int i;
 	if (num){
-		_printLine_("   Hook: ");
-		_printLine_("      num=" << this->num);
-		_printString_("      ids: ");
-		for (i=0;i<this->num;i++) _printString_(this->ids[i] << " ");
-		_printLine_("");
-		_printString_("      offsets: ");
-		for (i=0;i<this->num;i++) _printString_(this->offsets[i] << " ");
-		_printLine_("");
-		if (!objects) _printLine_("      warning: object not hooked yet");
+		_printf_("   Hook: \n");
+		_printf_("      num=" << this->num << "\n");
+		_printf_("      ids: ");
+		for (i=0;i<this->num;i++) _printf_(this->ids[i] << " ");
+		_printf_("\n");
+		_printf_("      offsets: ");
+		for (i=0;i<this->num;i++) _printf_(this->offsets[i] << " ");
+		_printf_("\n");
+		if (!objects) _printf_("      warning: object not hooked yet\n");
 		else{
-			_printString_("      objects:\n   ");
+			_printf_("      objects:\n   ");
 			for (i=0;i<this->num;i++){
-				_printLine_("         object " << i);
+				_printf_("         object " << i << "\n");
 				if(objects[i]) objects[i]->DeepEcho();
-				else           _printLine_("            no object hooked yet (not configured)");
+				else           _printf_("            no object hooked yet (not configured)\n");
 			}
 		}
 	}
 	else{
-		_printLine_("   Hook: num=0 ");
+		_printf_("   Hook: num=0 \n");
 	}
 }
Index: /issm/trunk/src/c/classes/Hook.h
===================================================================
--- /issm/trunk/src/c/classes/Hook.h	(revision 15395)
+++ /issm/trunk/src/c/classes/Hook.h	(revision 15396)
@@ -11,6 +11,5 @@
 /*Headers:*/
 /*{{{*/
-#include "./objects/Object.h"
-class DataSet;
+#include "../datastructures/datastructures.h"
 /*}}}*/
 
Index: /issm/trunk/src/c/classes/IndependentObject.cpp
===================================================================
--- /issm/trunk/src/c/classes/IndependentObject.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/IndependentObject.cpp	(revision 15396)
@@ -0,0 +1,216 @@
+/*!\file IndependentObject.c
+ * \brief: implementation of the IndependentObject object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./classes.h"
+#include "../shared/shared.h"
+#include "IoModel.h"
+
+/*IndependentObject constructors and destructor*/
+/*FUNCTION IndependentObject::IndependentObject(){{{*/
+IndependentObject::IndependentObject(){
+	this->name=NoneEnum;
+	this->type=0;
+	this->numberofindependents=0;
+}
+/*}}}*/
+/*FUNCTION IndependentObject::IndependentObject(int in_name, int in_type){{{*/
+IndependentObject::IndependentObject(int in_name, int in_type){
+
+	this->numberofindependents=0;
+	this->name=in_name;
+	this->type=in_type;
+	if(in_type!=0 && in_type!=1)_error_("cannot create an IndependentObject of type " << in_type);
+
+}
+/*}}}*/
+/*FUNCTION IndependentObject::~IndependentObject() {{{*/
+IndependentObject::~IndependentObject(){ //destructor
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IndependentObject::Echo{{{*/
+void IndependentObject::Echo(void){
+
+	_printf_("IndependentObject:\n");
+	_printf_("   name: " << EnumToStringx(this->name) << "\n");
+	if(this->type==0)
+		_printf_("   type: scalar\n");
+	else if(this->type==1)
+		_printf_("   type: vertex\n");
+	else
+		_error_(" unknown type: " << this->type);
+	_printf_("   numberofindependents: " << this->numberofindependents << "\n");
+}
+/*}}}*/
+/*FUNCTION IndependentObject::DeepEcho{{{*/
+void IndependentObject::DeepEcho(void){
+	this->Echo();
+}
+/*}}}*/
+/*FUNCTION IndependentObject::Id{{{*/
+int    IndependentObject::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IndependentObject::ObjectEnum{{{*/
+int IndependentObject::ObjectEnum(void){
+
+	return IndependentObjectEnum;
+
+}
+/*}}}*/
+/*FUNCTION IndependentObject::copy{{{*/
+Object* IndependentObject::copy(void) { 
+
+	IndependentObject* object=new IndependentObject();
+	object->name=this->name;
+	object->type=this->type;
+	object->numberofindependents=this->numberofindependents;
+
+	return  object;
+} /*}}}*/
+
+/*IndependentObject methods: */
+/*FUNCTION IndependentObject::FetchIndependent{{{*/
+void IndependentObject::FetchIndependent(IoModel* iomodel){
+
+	int my_rank;
+	FILE* fid=NULL;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	#ifdef _HAVE_ADOLC_ //cannot come here unless you are running AD mode, from DeclaredIndependents:
+
+	/*Branch according to the type of variable: */
+	if(type==0){ /*scalar: {{{*/
+
+		/*output: */
+		IssmPDouble  pscalar;
+		IssmDouble   scalar; //same as pscalar, except it's an ADOLC independent variable
+		IssmDouble*  scalar_slot=NULL;
+		int      code;
+
+		/*Set file pointer to beginning of the data: */
+		fid=iomodel->SetFilePointerToData(&code,NULL,name);
+
+		if(code!=3)_error_("expecting a IssmDouble for enum " << EnumToStringx(name));
+
+		/*We have to read a scalar from disk. First read the dimensions of the scalar, then the scalar: */
+		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
+
+		/*Ok, we are almost done. scalar is now an independent variable. We don't want this variable to be fetched again in the 
+		 *future, which would effectively write over the independency in the ADOLC tape! So we are going to keep track of this 
+		 independent variable inthe iomodel->data[name] data slot. Because this data slot holds double*, we allocate a sizeof(double)
+		 space for it: */
+		scalar_slot=xNew<IssmDouble>(1); *scalar_slot=scalar;
+
+		iomodel->data[name]=scalar_slot;
+		iomodel->independents[name]=true;
+
+		//finally, record the number of independents:
+		this->numberofindependents=1;
+
+	} /*}}}*/
+	else if(type==1){ /* vector: {{{*/
+
+		FILE* fid=NULL;
+		int M,N;
+		IssmPDouble* buffer=NULL; //a buffer to read the data from disk
+		IssmDouble* matrix=NULL; //our independent variable
+		int code=0;
+
+		/*Set file pointer to beginning of the data: */
+		fid=iomodel->SetFilePointerToData(&code,NULL,name);
+		if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(name));
+
+		/*We have to read a matrix from disk. First read the dimensions of the matrix, then the whole matrix: */
+		/*numberofelements: */
+		if(my_rank==0){  
+			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
+
+		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
+
+		/*Now allocate matrix: */
+		if(M*N){
+			buffer=xNew<IssmPDouble>(M*N);
+			matrix=xNew<IssmDouble>(M*N);
+
+			/*Read matrix on node 0, then broadcast: */
+			if(my_rank==0){  
+				if(fread(buffer,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
+
+				/*Now, before we even broadcast this to other nodes, declare the whole matrix as a independent variable!: */
+				for (int i=0;i<M*N;++i) matrix[i]<<=buffer[i];  /*we use the <<= ADOLC overloaded operator to declare the independency*/
+			}
+			#ifdef _HAVE_MPI_
+			MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm()); 
+			#endif
+
+			xDelete<IssmPDouble>(buffer);
+		}
+		else _error_("cannot declare the independent variable " << EnumToStringx(name) <<  "if it's empty!");
+
+		/*Ok, we are almost done. Matrix is now a independent matrix. We don't want this matrix to be fetched again in the 
+		 *future, which would effectively write over the independency in the ADOLC tape! So we are going to keep track of this 
+		 independent matrix inthe iomodel->data[name] data slot: */
+		iomodel->data[name]=matrix;
+		iomodel->independents[name]=true;
+		
+		//Finally, record the number of independents created: 
+		this->numberofindependents=M*N;
+
+	}/*}}}*/
+	else _error_("should not have a type of " << type);
+
+	#endif
+}
+/*}}}*/
+/*FUNCTION IndependentObject::NumIndependents{{{*/
+int  IndependentObject::NumIndependents(void){
+
+	return this->numberofindependents;;
+}
+/*}}}*/
+/*FUNCTION IndependentObject::FillIndependents{{{*/
+void IndependentObject::FillIndependents(IssmDouble** data, IssmDouble* xp){
+
+	int i;
+
+	/*Branch according to the type of variable: */
+	if(type==0){ /*scalar:*/
+		xp[0]=*(data[name]);
+	}
+	else if(type==1){ /* vector:*/
+		IssmDouble* values=data[name];
+		for(i=0;i<this->numberofindependents;i++){
+			xp[i]=values[i];
+		}
+	}
+	else _error_("should not have a type of " << type);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/IndependentObject.h
===================================================================
--- /issm/trunk/src/c/classes/IndependentObject.h	(revision 15396)
+++ /issm/trunk/src/c/classes/IndependentObject.h	(revision 15396)
@@ -0,0 +1,41 @@
+/*!\file: IndependentObject.h
+ * \brief prototype for IndependentObject.h
+ */ 
+
+#ifndef _INDEPENDENTOBJECT_H_
+#define  _INDEPENDENTOBJECT_H_
+
+/*{{{*/
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+/*}}}*/
+class IoModel;
+
+class IndependentObject: public Object{
+
+	public:
+
+		int name;
+		int type;  /*0: scalar, 1: vertex*/
+		int numberofindependents;
+
+		/*IndependentObject constructors, destructors {{{*/
+		IndependentObject();
+		IndependentObject(int name, int type);
+		~IndependentObject();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy(void);
+		/*}}}*/
+		/*IndependentObject methods: {{{*/
+		void FetchIndependent(IoModel* iomodel);
+		int  NumIndependents(void);
+		void FillIndependents(IssmDouble** data, IssmDouble* xp);
+		/*}}}*/
+
+};
+#endif //ifndef _INDEPENDENTOBJECT_H_
Index: /issm/trunk/src/c/classes/Inputs/BoolInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 15396)
@@ -0,0 +1,175 @@
+/*!\file BoolInput.c
+ * \brief: implementation of the BoolInput 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"
+
+/*BoolInput constructors and destructor*/
+/*FUNCTION BoolInput::BoolInput(){{{*/
+BoolInput::BoolInput(){
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolInput::BoolInput(int in_enum_type,bool in_value){{{*/
+BoolInput::BoolInput(int in_enum_type,bool in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION BoolInput::~BoolInput(){{{*/
+BoolInput::~BoolInput(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION BoolInput::Echo {{{*/
+void BoolInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION BoolInput::DeepEcho{{{*/
+void BoolInput::DeepEcho(void){
+
+	_printf_("BoolInput:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   value: " <<(value?"true":"false") << "\n");
+}
+/*}}}*/
+/*FUNCTION BoolInput::Id{{{*/
+int    BoolInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolInput::ObjectEnum{{{*/
+int BoolInput::ObjectEnum(void){
+
+	return BoolInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::copy{{{*/
+Object* BoolInput::copy() {
+
+	return new BoolInput(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*BoolInput management*/
+/*FUNCTION BoolInput::InstanceEnum{{{*/
+int BoolInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::SpawnTriaInput{{{*/
+Input* BoolInput::SpawnTriaInput(int* indices){
+
+		/*output*/
+		BoolInput* outinput=new BoolInput();
+
+		/*only copy current value*/
+		outinput->enum_type=this->enum_type;
+		outinput->value=this->value;
+
+		/*Assign output*/
+		return outinput;
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::SpawnResult{{{*/
+ElementResult* BoolInput::SpawnResult(int step, IssmDouble time){
+
+	return new BoolElementResult(this->enum_type,this->value,step,time);
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION BoolInput::GetInputValue(bool* pvalue) {{{*/
+void BoolInput::GetInputValue(bool* pvalue){
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(int* pvalue){{{*/
+void BoolInput::GetInputValue(int* pvalue){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue){{{*/
+void BoolInput::GetInputValue(IssmDouble* pvalue){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void BoolInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void BoolInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::ChangeEnum{{{*/
+void BoolInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION BoolInput::SquareMin{{{*/
+void BoolInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
+	/*square of a bool is the bool itself: */
+	*psquaremin=value;
+}
+/*}}}*/
+/*FUNCTION BoolInput::Scale{{{*/
+void BoolInput::Scale(IssmDouble scale_factor){
+	/*a bool cannot be scaled: */
+}
+/*}}}*/
+/*FUNCTION BoolInput::AXPY{{{*/
+void BoolInput::AXPY(Input* xinput,IssmDouble scalar){
+
+	BoolInput*  xboolinput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	xboolinput=(BoolInput*)xinput;
+
+	/*Carry out the AXPY operation depending on type:*/
+	switch(xinput->ObjectEnum()){
+
+		case BoolInputEnum:
+			this->value=reCast<bool,IssmDouble>(this->value+scalar*xboolinput->value);
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::Extrude{{{*/
+void BoolInput::Extrude(void){
+
+	/*do nothing*/
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolInput::GetVectorFromInputs{{{*/
+void BoolInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+
+	_error_("not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::Configure{{{*/
+void BoolInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/BoolInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/BoolInput.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/BoolInput.h	(revision 15396)
@@ -0,0 +1,84 @@
+/*! \file BoolInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _BOOLINPUT_H_
+#define _BOOLINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class GaussTria;
+class GaussPenta;
+/*}}}*/
+
+class BoolInput: public Input{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int  enum_type;
+		bool value;
+
+		/*BoolInput constructors, destructors: {{{*/
+		BoolInput();
+		BoolInput(int enum_type,bool value);
+		~BoolInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*BoolInput management: {{{*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void Configure(Parameters* parameters);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		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);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		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){_error_("not implemented yet");};
+		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 ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin, Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("InfinityNorm not implemented for booleans");};
+		IssmDouble Max(void){_error_("Max not implemented for booleans");};
+		IssmDouble MaxAbs(void){_error_("Max not implemented for booleans");};
+		IssmDouble Min(void){_error_("Min not implemented for booleans");};
+		IssmDouble MinAbs(void){_error_("Min not implemented for booleans");};
+		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){_error_("Constrain not implemented for booleans");};
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		/*}}}*/
+
+};
+#endif  /* _BOOLINPUT_H */
Index: /issm/trunk/src/c/classes/Inputs/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Inputs/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,16 @@
+# 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 15396)
+++ /issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 15396)
@@ -0,0 +1,271 @@
+/*!\file ControlInput.c
+ * \brief: implementation of the ControlInput 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"
+
+/*ControlInput constructors and destructor*/
+/*FUNCTION ControlInput::ControlInput(){{{*/
+ControlInput::ControlInput(){
+	control_id  = 0;
+	values      = NULL;
+	savedvalues = NULL;
+	minvalues   = NULL;
+	maxvalues   = NULL;
+	gradient    = NULL;
+}
+/*}}}*/
+/*FUNCTION ControlInput::ControlInput(int enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int id){{{*/
+ControlInput::ControlInput(int in_enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int id){
+
+	control_id=id;
+	enum_type=in_enum_type;
+
+	switch(enum_input){
+		case TriaInputEnum:
+			values     =new TriaInput(enum_type,pvalues,P1Enum);
+			savedvalues=new TriaInput(enum_type,pvalues,P1Enum);
+			minvalues  =new TriaInput(enum_type,pmin,P1Enum);
+			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);
+			break;
+		default:
+			_error_("Input of Enum " << EnumToStringx(enum_input) << " not supported yet by ControlInput");
+	}
+	gradient   =NULL;
+}
+/*}}}*/
+/*FUNCTION ControlInput::~ControlInput(){{{*/
+ControlInput::~ControlInput(){
+	delete values;
+	delete savedvalues;
+	delete minvalues;
+	delete maxvalues;
+	delete gradient;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+		/*FUNCTION ControlInput::Echo {{{*/
+void ControlInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION ControlInput::DeepEcho{{{*/
+void ControlInput::DeepEcho(void){
+
+	_printf_("ControlInput:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("---values: \n");     if (values)      values->Echo();
+	_printf_("---savedvalues: \n");if (savedvalues) savedvalues->Echo();
+	_printf_("---minvalues: \n");  if (minvalues)   minvalues->Echo();
+	_printf_("---maxvalues: \n");  if (maxvalues)   maxvalues->Echo();
+	_printf_("---gradient: \n");   if (gradient)    gradient->Echo();
+}
+/*}}}*/
+/*FUNCTION ControlInput::Id{{{*/
+int    ControlInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION ControlInput::ObjectEnum{{{*/
+int ControlInput::ObjectEnum(void){
+
+	return ControlInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION ControlInput::copy{{{*/
+Object* ControlInput::copy() {
+
+	ControlInput* output=NULL;
+
+	output = new ControlInput();
+	output->enum_type=this->enum_type;
+	output->control_id=this->control_id;
+
+	if(values)      output->values      = dynamic_cast<Input*>(this->values->copy());
+	if(savedvalues) output->savedvalues = dynamic_cast<Input*>(this->savedvalues->copy());
+	if(minvalues)   output->minvalues   = dynamic_cast<Input*>(this->minvalues->copy());
+	if(maxvalues)   output->maxvalues   = dynamic_cast<Input*>(this->maxvalues->copy());
+	if(gradient)    output->gradient    = dynamic_cast<Input*>(this->gradient->copy());
+
+	return output;
+}
+/*}}}*/
+
+/*ControlInput management*/
+/*FUNCTION ControlInput::InstanceEnum{{{*/
+int ControlInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION ControlInput::Constrain(){{{*/
+void ControlInput::Constrain(void){
+
+	Input* newvalues=NULL;
+
+	newvalues=this->values->PointwiseMin(maxvalues);
+	delete values; this->values=newvalues;
+	newvalues=this->values->PointwiseMax(minvalues);
+	delete values; this->values=newvalues;
+}/*}}}*/
+/*FUNCTION ControlInput::Constrain(IssmDouble min, IssmDouble max){{{*/
+void ControlInput::Constrain(IssmDouble min, IssmDouble max){
+	   values->Constrain(min,max);
+}/*}}}*/
+/*FUNCTION ControlInput::Extrude{{{*/
+void ControlInput::Extrude(void){
+	values->Extrude();
+	savedvalues->Extrude();
+	//gradient->Extrude();
+}/*}}}*/
+/*FUNCTION ControlInput::GetGradient{{{*/
+void ControlInput::GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist){
+	if(gradient) gradient->GetVectorFromInputs(gradient_vec,doflist);
+}/*}}}*/
+/*FUNCTION ControlInput::ScaleGradient{{{*/
+void ControlInput::ScaleGradient(IssmDouble scaling_factor){
+	if(!gradient) _error_("Gradient of ControlInput " << EnumToStringx(enum_type) << " not found");
+	gradient->Scale(scaling_factor);
+}/*}}}*/
+/*FUNCTION ControlInput::SetGradient{{{*/
+void ControlInput::SetGradient(Input* gradient_in){
+
+	/*Get enum for current gradient*/
+	switch(this->control_id){
+		case 1:
+			gradient_in->ChangeEnum(Gradient1Enum);
+			break;
+		case 2:
+			gradient_in->ChangeEnum(Gradient2Enum);
+			break;
+		case 3:
+			gradient_in->ChangeEnum(Gradient3Enum);
+			break;
+		default:
+			_error_("more than 3 controls not implemented yet (Gradient " << this->control_id << " was requested). EnumDefinitions.h needs to be updated.");
+	}
+
+	/*Delete old gradient and assign new gradient*/
+	if(gradient) delete gradient;
+	gradient=gradient_in;
+
+}/*}}}*/
+/*FUNCTION ControlInput::SetInput{{{*/
+void ControlInput::SetInput(Input* in_input){
+
+	delete values; this->values=in_input;
+	this->SaveValue(); //because this is what SpawnResult saves FIXME
+
+}/*}}}*/
+/*FUNCTION ControlInput::SpawnResult{{{*/
+ElementResult* ControlInput::SpawnResult(int step, IssmDouble time){
+	return savedvalues->SpawnResult(step,time);
+}/*}}}*/
+/*FUNCTION ControlInput::SpawnTriaInput{{{*/
+Input* ControlInput::SpawnTriaInput(int* indices){
+	return values->SpawnTriaInput(indices);
+}/*}}}*/
+/*FUNCTION ControlInput::SpawnGradient{{{*/
+ElementResult* ControlInput::SpawnGradient(int step, IssmDouble time){
+	_assert_(gradient);
+	return gradient->SpawnResult(step,time);
+}/*}}}*/
+/*FUNCTION ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){{{*/
+void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+	values->GetVectorFromInputs(vector,doflist);
+}/*}}}*/
+/*FUNCTION ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data){{{*/
+void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data){
+	 if(strcmp(data,"value")==0){
+		 _assert_(values);
+		 values->GetVectorFromInputs(vector,doflist);
+	 }
+	 else if (strcmp(data,"lowerbound")==0){
+		 _assert_(minvalues);
+		 minvalues->GetVectorFromInputs(vector,doflist);
+	 }
+	 else if (strcmp(data,"upperbound")==0){
+		 _assert_(maxvalues);
+		 maxvalues->GetVectorFromInputs(vector,doflist);
+	 }
+	 else if (strcmp(data,"gradient")==0){
+		 _assert_(gradient);
+		 gradient->GetVectorFromInputs(vector,doflist);
+	 }
+	 else{
+		 _error_("Data " << data << " not supported yet");
+	 }
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputAverage(IssmDouble* pvalue){{{*/
+void ControlInput::GetInputAverage(IssmDouble* pvalue){
+	values->GetInputAverage(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(bool* pvalue){{{*/
+void ControlInput::GetInputValue(bool* pvalue){
+	values->GetInputValue(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(int* pvalue){{{*/
+void ControlInput::GetInputValue(int* pvalue){
+	values->GetInputValue(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(IssmDouble* pvalue){{{*/
+void ControlInput::GetInputValue(IssmDouble* pvalue){
+	values->GetInputValue(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(IssmDouble* pvalue){{{*/
+void ControlInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){
+	values->GetInputValue(pvalue,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(IssmDouble* pvalue){{{*/
+void ControlInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){
+	values->GetInputValue(pvalue,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){
+	values->GetInputDerivativeValue(derivativevalues,xyz_list,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){
+	values->GetInputDerivativeValue(derivativevalues,xyz_list,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::SaveValue{{{*/
+void ControlInput::SaveValue(void){
+	if(!values) _error_("Values of " << EnumToStringx(this->enum_type) << " not found");
+
+	if(savedvalues) delete this->savedvalues;
+	this->savedvalues=dynamic_cast<Input*>(this->values->copy());
+}/*}}}*/
+/*FUNCTION ControlInput::UpdateValue{{{*/
+void ControlInput::UpdateValue(IssmDouble scalar){
+	if(!gradient)    _error_("Gradient of " << EnumToStringx(this->enum_type) << " not found");
+	if(!savedvalues) _error_("Values of " << EnumToStringx(this->enum_type) << " not found");
+
+	if(values) delete this->values;
+	this->values=dynamic_cast<Input*>(this->savedvalues->copy());
+	this->values->AXPY(gradient,scalar);
+}/*}}}*/
+/*FUNCTION ControlInput::VerticallyIntegrate{{{*/
+void ControlInput::VerticallyIntegrate(Input* thickness_input){
+	values->VerticallyIntegrate(thickness_input);
+}/*}}}*/
+/*FUNCTION ControlInput::Configure{{{*/
+void ControlInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/ControlInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 15396)
@@ -0,0 +1,97 @@
+/*! \file ControlInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _CONTROLINPUT_H_
+#define _CONTROLINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class GaussTria;
+class GaussPenta;
+/*}}}*/
+
+class ControlInput: public Input{
+
+	public:
+		int    enum_type;
+		int    control_id;
+		Input* values;
+		Input* savedvalues;
+		Input* minvalues;
+		Input* maxvalues;
+		Input* gradient;
+
+		/*ControlInput constructors, destructors: {{{*/
+		ControlInput();
+		ControlInput(int enum_type,int enum_input,IssmDouble* pvalues,IssmDouble* pmin,IssmDouble* pmax,int id);
+		~ControlInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ControlInput management: {{{*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void SetInput(Input* in_input);
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		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);
+		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){_error_("not implemented yet");};
+		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 ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		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 Constrain(void);
+		void Constrain(IssmDouble min,IssmDouble max);
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void){_error_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error_("not implemented yet");};
+		IssmDouble Min(void){_error_("not implemented yet");};
+		IssmDouble MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		ElementResult* SpawnGradient(int step, IssmDouble time);
+		void GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist);
+		void ScaleGradient(IssmDouble scale);
+		void SetGradient(Input* gradient_in);
+		void UpdateValue(IssmDouble scalar);
+		void SaveValue(void);
+		/*}}}*/
+
+};
+#endif  /* _CONTROLINPUT_H */
Index: /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 15396)
@@ -0,0 +1,111 @@
+/*!\file DatasetInput.c
+ * \brief: implementation of the datasetinput 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"
+/*}}}*/
+
+/*DatasetInput constructors and destructor*/
+/*FUNCTION DatasetInput::DatasetInput(){{{*/
+DatasetInput::DatasetInput(){
+	enum_type=UNDEF;
+	inputs=NULL;
+}
+/*}}}*/
+/*FUNCTION DatasetInput::DatasetInput(int in_enum_type) {{{*/
+DatasetInput::DatasetInput(int in_enum_type){
+
+	enum_type  = in_enum_type;
+	inputs     = new Inputs();
+}
+/*}}}*/
+/*FUNCTION DatasetInput::~DatasetInput(){{{*/
+DatasetInput::~DatasetInput(){
+	delete inputs;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+		/*FUNCTION DatasetInput::Echo {{{*/
+void DatasetInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DatasetInput::DeepEcho{{{*/
+void DatasetInput::DeepEcho(void){
+
+	_printf_("DatasetInput:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("---inputs: \n"); inputs->Echo();
+}
+/*}}}*/
+/*FUNCTION DatasetInput::Id{{{*/
+int    DatasetInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DatasetInput::ObjectEnum{{{*/
+int DatasetInput::ObjectEnum(void){
+
+	return DatasetInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION DatasetInput::copy{{{*/
+Object* DatasetInput::copy() {
+
+	DatasetInput* output=NULL;
+
+	output = new DatasetInput();
+	output->enum_type=this->enum_type;
+	output->inputs=(Inputs*)this->inputs->Copy();
+
+	return output;
+}
+/*}}}*/
+/*FUNCTION DatasetInput::SpawnTriaInput{{{*/
+Input* DatasetInput::SpawnTriaInput(int* indices){
+
+	/*output*/
+	DatasetInput* outinput=NULL;
+
+	/*Create new Datasetinput (copy of current input)*/
+	outinput=new DatasetInput();
+	outinput->enum_type=this->enum_type;
+	outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnTriaInputs(indices));
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+
+/*DatasetInput management*/
+/*FUNCTION DatasetInput::InstanceEnum{{{*/
+int DatasetInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION DatasetInput::Configure{{{*/
+void DatasetInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
+/*FUNCTION DatasetInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,int index){{{*/
+void DatasetInput::GetInputValue(IssmDouble* pvalue,GaussTria* 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 15396)
+++ /issm/trunk/src/c/classes/Inputs/DatasetInput.h	(revision 15396)
@@ -0,0 +1,90 @@
+/*! \file DatasetInput.h 
+ *  \brief: header file for datasetinput object
+ */
+
+#ifndef _DATASETINPUT_H_
+#define _DATASETINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class GaussTria;
+class GaussPenta;
+/*}}}*/
+
+class DatasetInput: public Input{
+
+	public:
+		int     enum_type;
+		Inputs *inputs;
+
+		/*DatasetInput constructors, destructors: {{{*/
+		DatasetInput();
+		DatasetInput(int enum_type);
+		~DatasetInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*DatasetInput management: {{{*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time){_error_("not implemented yet");};
+		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){_error_("not implemented yet");};
+		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);
+		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){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		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){_error_("not implemented yet");};
+		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 ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		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 Constrain(void){_error_("not implemented yet");};
+		void Constrain(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void){_error_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error_("not implemented yet");};
+		IssmDouble Min(void){_error_("not implemented yet");};
+		IssmDouble MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void){_error_("not implemented yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not implemented yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_error_("not implemented yet");};
+		ElementResult* SpawnGradient(int step, IssmDouble time){_error_("not implemented yet");};
+		void GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist){_error_("not implemented yet");};
+		void ScaleGradient(IssmDouble scale){_error_("not implemented yet");};
+		void SetGradient(Input* gradient_in){_error_("not implemented yet");};
+		void UpdateValue(IssmDouble scalar){_error_("not implemented yet");};
+		void SaveValue(void){_error_("not implemented yet");};
+		/*}}}*/
+
+};
+#endif  /* _DATASETINPUT_H */
Index: /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp	(revision 15396)
@@ -0,0 +1,341 @@
+/*!\file DoubleInput.c
+ * \brief: implementation of the DoubleInput 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"
+
+/*DoubleInput constructors and destructor*/
+/*FUNCTION DoubleInput::DoubleInput(){{{*/
+DoubleInput::DoubleInput(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::DoubleInput(IssmDouble value){{{*/
+DoubleInput::DoubleInput(int in_enum_type,IssmDouble in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::~DoubleInput(){{{*/
+DoubleInput::~DoubleInput(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+		/*FUNCTION DoubleInput::Echo {{{*/
+void DoubleInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DoubleInput::DeepEcho{{{*/
+void DoubleInput::DeepEcho(void){
+
+	_printf_("DoubleInput:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   value: " << this->value << "\n");
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Id{{{*/
+int    DoubleInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleInput::ObjectEnum{{{*/
+int DoubleInput::ObjectEnum(void){
+
+	return DoubleInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::copy{{{*/
+Object* DoubleInput::copy() {
+
+	return new DoubleInput(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*DoubleInput management*/
+/*FUNCTION DoubleInput::InstanceEnum{{{*/
+int DoubleInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::SpawnTriaInput{{{*/
+Input* DoubleInput::SpawnTriaInput(int* indices){
+
+	/*output*/
+	DoubleInput* outinput=new DoubleInput();
+
+	/*only copy current value*/
+	outinput->enum_type=this->enum_type;
+	outinput->value=this->value;
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::SpawnResult{{{*/
+ElementResult* DoubleInput::SpawnResult(int step, IssmDouble time){
+
+	return new DoubleElementResult(this->enum_type,this->value,step,time);
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION DoubleInput::GetInputValue(bool* pvalue) {{{*/
+void DoubleInput::GetInputValue(bool* pvalue){
+	_error_("Double input of enum " << EnumToStringx(enum_type) << " cannot return a boolean");
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(int* pvalue){{{*/
+void DoubleInput::GetInputValue(int* pvalue){
+	_error_("Double input of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(IssmDouble* pvalue){{{*/
+void DoubleInput::GetInputValue(IssmDouble* pvalue){
+
+	/*return value*/
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void DoubleInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){*pvalue=this->value;}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void DoubleInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){*pvalue=this->value;}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void DoubleInput::GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){
+	/*Epsilon is zero as vx is constant over the element*/
+	for(int i=0;i<3;i++) epsilonvx[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void DoubleInput::GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){
+	/*Epsilon is zero as vy is constant over the element*/
+	for(int i=0;i<3;i++) epsilonvy[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vx is constant over the element*/
+	for(int i=0;i<6;i++) epsilonvx[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vy is constant over the element*/
+	for(int i=0;i<6;i++) epsilonvy[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vz is constant over the element*/
+	for(int i=0;i<6;i++) epsilonvz[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVxStrainRate3dPattyn(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){
+	/*Epsilon is zero as vy is constant over the element*/
+	for(int i=0;i<5;i++) epsilonvy[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::ChangeEnum{{{*/
+void DoubleInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::SquareMin{{{*/
+void DoubleInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
+
+	/*square min of a IssmDouble is the square of the IssmDouble itself: */
+	*psquaremin=pow(value,2);
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Scale{{{*/
+void DoubleInput::Scale(IssmDouble scale_factor){
+	value=value*scale_factor;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::ConstrainMin{{{*/
+void DoubleInput::ConstrainMin(IssmDouble minimum){
+	if (value<minimum) value=minimum;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::AXPY{{{*/
+void DoubleInput::AXPY(Input* xinput,IssmDouble scalar){
+
+	DoubleInput*  xIssmDoubleinput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	xIssmDoubleinput=(DoubleInput*)xinput;
+
+	/*Carry out the AXPY operation depending on type:*/
+	switch(xinput->ObjectEnum()){
+
+		case DoubleInputEnum:
+			this->value=this->value+scalar*xIssmDoubleinput->value;
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Constrain{{{*/
+void DoubleInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+
+	if(!xIsNan<IssmDouble>(cm_min)) if (this->value<cm_min)this->value=cm_min;
+	if(!xIsNan<IssmDouble>(cm_max)) if (this->value>cm_max)this->value=cm_max;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Max{{{*/
+IssmDouble DoubleInput::Max(void){
+	return this->value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::MaxAbs{{{*/
+IssmDouble DoubleInput::MaxAbs(void){
+	return fabs(this->value);
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Min{{{*/
+IssmDouble DoubleInput::Min(void){
+	return this->value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::MinAbs{{{*/
+IssmDouble DoubleInput::MinAbs(void){
+	return fabs(this->value);
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVectorFromInputs{{{*/
+void DoubleInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+
+	_error_("not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputAverage{{{*/
+void DoubleInput::GetInputAverage(IssmDouble* pvalue){
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::VerticallyIntegrate{{{*/
+void DoubleInput::VerticallyIntegrate(Input* thickness_input){
+
+	/*Intermediaries*/
+	IssmDouble thickness_value;
+
+	/*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:
+			thickness_input->GetInputAverage(&thickness_value);
+			this->value=this->value*thickness_value;
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleInput::PointwiseDivide{{{*/
+Input* DoubleInput::PointwiseDivide(Input* inputB){
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	IssmDouble       Bvalue;
+
+	/*Check that inputB is of the same type*/
+	inputB->GetInputAverage(&Bvalue);
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,this->value/Bvalue);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::PointwiseMin{{{*/
+Input* DoubleInput::PointwiseMin(Input* input){
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	IssmDouble       min;
+
+	/*Check that inputB is of the same type*/
+	if (input->Min() < this->Min()) min=input->Min();
+	else min=this->Min();
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,min);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::PointwiseMax{{{*/
+Input* DoubleInput::PointwiseMax(Input* input){
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	IssmDouble       max;
+
+	/*Check that inputB is of the same type*/
+	if (input->Max() > this->Max()) max=input->Max();
+	else max=this->Max();
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,max);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Configure{{{*/
+void DoubleInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/DoubleInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DoubleInput.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/DoubleInput.h	(revision 15396)
@@ -0,0 +1,83 @@
+/*! \file DoubleInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DOUBLEINPUT_H_
+#define _DOUBLEINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class GaussTria;
+class GaussPenta;
+/*}}}*/
+
+class DoubleInput: public Input{
+
+	public:
+		int    enum_type;
+		IssmDouble value;
+
+		/*DoubleInput constructors, destructors: {{{*/
+		DoubleInput();
+		DoubleInput(int enum_type,IssmDouble value);
+		~DoubleInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*DoubleInput 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);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		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);
+		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);
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss);
+		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){_error_("not implemented yet");};
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		/*}}}*/
+
+};
+#endif  /* _DOUBLEINPUT_H */
Index: /issm/trunk/src/c/classes/Inputs/Input.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Input.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/Input.h	(revision 15396)
@@ -0,0 +1,72 @@
+/*!\file:  Input.h
+ * \brief abstract class for Input object
+ */ 
+
+#ifndef _INPUT_H_
+#define _INPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+class Node;
+class ElementResult;
+class GaussTria;
+class Parameters;
+class GaussPenta;
+template <class doubletype> class Vector;
+/*}}}*/
+
+class Input: public Object{
+
+	public: 
+
+		virtual        ~Input(){};
+
+		virtual int  InstanceEnum()=0; 
+		virtual void GetInputValue(bool* pvalue)=0;
+		virtual void GetInputValue(int* pvalue)=0;
+		virtual void GetInputValue(IssmDouble* pvalue)=0;
+		virtual void GetInputValue(IssmDouble* pvalue,GaussTria* gauss)=0;
+		virtual void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss)=0;
+		virtual void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time)=0;
+		virtual void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time)=0;
+		virtual void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index)=0;
+		virtual void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index)=0;
+		virtual void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss)=0;
+		virtual void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss)=0;
+		virtual void GetInputAverage(IssmDouble* pvalue)=0;
+		virtual void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes)=0;
+		virtual void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime)=0;
+		virtual void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss)=0;
+		virtual void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss)=0;
+		virtual void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss)=0;
+		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 ChangeEnum(int newenumtype)=0;
+		virtual void Configure(Parameters* parameters)=0;
+
+		virtual void   SquareMin(IssmDouble* psquaremin,Parameters* parameters)=0;
+		virtual void   ConstrainMin(IssmDouble minimum)=0;
+		virtual IssmDouble InfinityNorm(void)=0;
+		virtual IssmDouble MaxAbs(void)=0;
+		virtual IssmDouble MinAbs(void)=0;
+		virtual IssmDouble Max(void)=0;
+		virtual IssmDouble Min(void)=0;
+		virtual void   Scale(IssmDouble scale_factor)=0;
+		virtual void   ArtificialNoise(IssmDouble min,IssmDouble max)=0;
+		virtual void   AXPY(Input* xinput,IssmDouble scalar)=0;
+		virtual void   Constrain(IssmDouble cm_min, IssmDouble cm_max)=0;
+		virtual void   VerticallyIntegrate(Input* thickness_input)=0;
+		virtual void   Extrude()=0;
+		virtual void   GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist)=0;
+
+		virtual Input* SpawnTriaInput(int* indices)=0;
+		virtual Input* PointwiseDivide(Input* inputB)=0;
+		virtual Input* PointwiseMax(Input* inputmax)=0;
+		virtual Input* PointwiseMin(Input* inputmin)=0;
+		virtual ElementResult* SpawnResult(int step, IssmDouble time)=0;
+};
+#endif
Index: /issm/trunk/src/c/classes/Inputs/Inputs.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 15396)
@@ -0,0 +1,426 @@
+/*
+ * \file Inputs.c
+ * \brief: implementation of the Inputs class, derived from DataSet class
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Input.h"
+#include "./Inputs.h"
+#include "../../shared/shared.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Inputs::Inputs(){{{*/
+Inputs::Inputs(){
+	return;
+}
+/*}}}*/
+/*FUNCTION Inputs::~Inputs(){{{*/
+Inputs::~Inputs(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Inputs::GetInputValue(bool* pvalue,int enum-type){{{*/
+void Inputs::GetInputValue(bool* pvalue,int enum_type){
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+	bool   found=false;
+
+	/*Go through inputs and check whether any input with the same name is already in: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+		if (input->InstanceEnum()==enum_type){
+			found=true;
+			break;
+		}
+	}
+
+	if (!found){
+		/*we could not find an input with the correct enum type. No defaults values were provided, 
+		 * error out: */
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputValue(pvalue);
+
+}
+/*}}}*/
+/*FUNCTION Inputs::GetInputValue(int* pvalue,int enum-type){{{*/
+void Inputs::GetInputValue(int* pvalue,int enum_type){
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+	bool   found=false;
+
+	/*Go through inputs and check whether any input with the same name is already in: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+		if (input->InstanceEnum()==enum_type){
+			found=true;
+			break;
+		}
+	}
+
+	if (!found){
+		/*we could not find an input with the correct enum type. No defaults values were provided, 
+		 * error out: */
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputValue(pvalue);
+
+}
+/*}}}*/
+/*FUNCTION Inputs::GetInputValue(IssmDouble* pvalue,int enum-type){{{*/
+void Inputs::GetInputValue(IssmDouble* pvalue,int enum_type){
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+	bool   found=false;
+
+	/*Go through inputs and check whether any input with the same name is already in: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object); 
+		if (input->InstanceEnum()==enum_type){
+			found=true;
+			break;
+		}
+	}
+
+	if (!found){
+		/*we could not find an input with the correct enum type. No defaults values were provided, 
+		 * error out: */
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputValue(pvalue);
+
+}
+/*}}}*/
+/*FUNCTION Inputs::GetInputAverage{{{*/
+void Inputs::GetInputAverage(IssmDouble* pvalue,int enum_type){
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+	bool   found=false;
+
+	/*Go through inputs and check whether any input with the same name is already in: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+		if (input->InstanceEnum()==enum_type){
+			found=true;
+			break;
+		}
+	}
+
+	if (!found){
+		/*we could not find an input with the correct enum type. No defaults values were provided, 
+		 * error out: */
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputAverage(pvalue);
+
+}
+/*}}}*/
+/*FUNCTION Inputs::AddInput{{{*/
+int  Inputs::AddInput(Input* in_input){
+
+	/*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;
+	Input* input=NULL;
+
+	/*In debugging mode, check that the input is not a NULL pointer*/
+	_assert_(in_input);
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+
+		if (input->InstanceEnum()==in_input->InstanceEnum()){
+			this->DeleteObject(input);
+			break;
+		}
+	}
+	this->AddObject(in_input);
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Inputs::ChangeEnum{{{*/
+void  Inputs::ChangeEnum(int oldenumtype,int newenumtype){
+
+	/*Go through dataset of inputs and look for input with 
+	 * same enum as input enum, once found, just change its name */
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	/*Delete existing input of newenumtype if it exists*/
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+		input=dynamic_cast<Input*>(*object);
+
+		if (input->InstanceEnum()==newenumtype){
+			this->DeleteObject(input);
+			break;
+		}
+	}
+
+	/*Change enum_type of input of oldenumtype*/
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+
+		if (input->InstanceEnum()==oldenumtype){
+			input->ChangeEnum(newenumtype);
+			break;
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Inputs::ConstrainMin{{{*/
+void  Inputs::ConstrainMin(int constrain_enum, IssmDouble minimum){
+
+	/*Find x and y inputs: */
+	Input* constrain_input=dynamic_cast<Input*>(this->GetInput(constrain_enum));
+
+	/*some checks: */
+	if(!constrain_input) _error_("input " << EnumToStringx(constrain_enum) << " could not be found!");
+
+	/*Apply ContrainMin: */
+	constrain_input->ConstrainMin(minimum);
+}
+/*}}}*/
+/*FUNCTION Inputs::InfinityNorm{{{*/
+IssmDouble Inputs::InfinityNorm(int enumtype){
+
+	/*Output*/
+	IssmDouble norm;
+
+	/*Get input*/
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+
+	/*Apply ContrainMin: */
+	if (input){
+		norm=input->InfinityNorm();
+	}
+	else{
+		norm=0;
+	}
+
+	/*Return output*/
+	return norm;
+}
+/*}}}*/
+/*FUNCTION Inputs::Max{{{*/
+IssmDouble Inputs::Max(int enumtype){
+
+	/*Output*/
+	IssmDouble max;
+
+	/*Get input*/
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+
+	/*Apply ContrainMin: */
+	if (input){
+		max=input->Max();
+	}
+	else{
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
+	}
+
+	/*Return output*/
+	return max;
+}
+/*}}}*/
+/*FUNCTION Inputs::MaxAbs{{{*/
+IssmDouble Inputs::MaxAbs(int enumtype){
+
+	/*Output*/
+	IssmDouble max;
+
+	/*Get input*/
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+
+	/*Apply ContrainMin: */
+	if (input){
+		max=input->MaxAbs();
+	}
+	else{
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
+	}
+
+	/*Return output*/
+	return max;
+}
+/*}}}*/
+/*FUNCTION Inputs::Min{{{*/
+IssmDouble Inputs::Min(int enumtype){
+
+	/*Output*/
+	IssmDouble min;
+
+	/*Get input*/
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+
+	/*Apply ContrainMin: */
+	if (input){
+		min=input->Min();
+	}
+	else{
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
+	}
+
+	/*Return output*/
+	return min;
+}
+/*}}}*/
+/*FUNCTION Inputs::MinAbs{{{*/
+IssmDouble Inputs::MinAbs(int enumtype){
+
+	/*Output*/
+	IssmDouble min;
+
+	/*Get input*/
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+
+	/*Apply ContrainMin: */
+	if (input){
+		min=input->MinAbs();
+	}
+	else{
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
+	}
+
+	/*Return output*/
+	return min;
+}
+/*}}}*/
+/*FUNCTION Inputs::GetInput{{{*/
+Input* Inputs::GetInput(int enum_name){
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+
+		if (input->InstanceEnum()==enum_name){
+			return input;
+		}
+	}
+	return NULL;
+}
+/*}}}*/
+/*FUNCTION Inputs::DeleteInput{{{*/
+int  Inputs::DeleteInput(int enum_type){
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+
+		if (input->InstanceEnum()==enum_type){
+			this->DeleteObject(input);
+			break;
+		}
+	}
+
+	return 1;
+
+}
+/*}}}*/
+/*FUNCTION Inputs::DuplicateInput{{{*/
+void  Inputs::DuplicateInput(int original_enum,int new_enum){
+
+	/*Make a copy of the original input: */
+	Input* original=dynamic_cast<Input*>(this->GetInput(original_enum));
+	if(!original)_error_("could not find input with enum: " << EnumToStringx(original_enum)); 
+	Input* copy=dynamic_cast<Input*>(original->copy());
+
+	/*Change copy enum to reinitialized_enum: */
+	copy->ChangeEnum(new_enum);
+
+	/*Add copy into inputs, it will wipe off the one already there: */
+	this->AddInput(dynamic_cast<Input*>(copy));
+}
+/*}}}*/
+/*FUNCTION Inputs::SpawnTriaInputs{{{*/
+Inputs* Inputs::SpawnTriaInputs(int* indices){
+
+	/*Intermediary*/
+	vector<Object*>::iterator object;
+	Input* inputin=NULL;
+	Input* inputout=NULL;
+
+	/*Output*/
+	Inputs* newinputs=new Inputs();
+
+	/*Go through inputs and call Spawn function*/
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Create new input*/
+		inputin=dynamic_cast<Input*>(*object);
+		inputout=inputin->SpawnTriaInput(indices);
+
+		/*Add input to new inputs*/
+		newinputs->AddObject(inputout);
+	}
+
+	/*Assign output pointer*/
+	return newinputs;
+}
+/*}}}*/
+/*FUNCTION Inputs::AXPY{{{*/
+void  Inputs::AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum){
+
+	/*Find x and y inputs: */
+	Input* xinput=dynamic_cast<Input*>(this->GetInput(MeshXEnum));
+	Input* yinput=dynamic_cast<Input*>(this->GetInput(MeshYEnum));
+
+	/*some checks: */
+	if(!xinput) _error_("input " << EnumToStringx(MeshXEnum) << " could not be found!");
+	if(!yinput) _error_("input " << EnumToStringx(MeshYEnum) << " could not be found!");
+
+	/*Apply AXPY: */
+	yinput->AXPY(xinput,scalar);
+}
+/*}}}*/
+/*FUNCTION Inputs::Configure{{{*/
+void Inputs::Configure(Parameters* parameters){
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=dynamic_cast<Input*>(*object);
+		input->Configure(parameters);
+
+	}
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/Inputs.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Inputs.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/Inputs.h	(revision 15396)
@@ -0,0 +1,45 @@
+#ifndef _CONTAINER_INPUTS_H_
+#define _CONTAINER_INPUTS_H_
+
+/*forward declarations */
+class Parameters;
+class Input;
+
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+
+/*! \brief Declaration of Inputs class.
+ *
+ * Declaration of Inputs class.  Inputs are vector lists (Containers) of Input objects.
+ */ 
+class Inputs: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Inputs();
+		~Inputs();
+
+		/*numerics*/
+		int        AddInput(Input* in_input);
+		void       ChangeEnum(int enumtype,int new_enumtype);
+		void       ConstrainMin(int constrain_enum, IssmDouble minimum);
+		int        DeleteInput(int enum_type);
+		void       DuplicateInput(int original_enum,int new_enum);
+		Input*     GetInput(int enum_name);
+		Inputs*    SpawnTriaInputs(int* indices);
+		void       AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum);
+		IssmDouble  InfinityNorm(int enumtype);
+		IssmDouble  Max(int enumtype);
+		IssmDouble  MaxAbs(int enumtype);
+		IssmDouble  Min(int enumtype);
+		IssmDouble  MinAbs(int enumtype);
+		void GetInputAverage(IssmDouble* pvalue, int enum_type);
+		void GetInputValue(bool* pvalue,int enum_type);
+		void GetInputValue(int* pvalue,int enum_type);
+		void GetInputValue(IssmDouble* pvalue,int enum_type);
+		void Configure(Parameters* parameters);
+
+};
+
+#endif //ifndef _INPUTS_H_
Index: /issm/trunk/src/c/classes/Inputs/IntInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/IntInput.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/IntInput.cpp	(revision 15396)
@@ -0,0 +1,181 @@
+/*!\file IntInput.c
+ * \brief: implementation of the IntInput 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"
+
+/*IntInput constructors and destructor*/
+/*FUNCTION IntInput::IntInput(){{{*/
+IntInput::IntInput(){
+	return;
+}
+/*}}}*/
+/*FUNCTION IntInput::IntInput(IssmDouble* values){{{*/
+IntInput::IntInput(int in_enum_type,IssmInt in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION IntInput::~IntInput(){{{*/
+IntInput::~IntInput(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IntInput::DeepEcho{{{*/
+void IntInput::DeepEcho(void){
+
+	_printf_("IntInput:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   value: " << (int)this->value << "\n");
+}
+/*}}}*/
+/*FUNCTION IntInput::Id{{{*/
+int    IntInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntInput::ObjectEnum{{{*/
+int IntInput::ObjectEnum(void){
+
+	return IntInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION IntInput::copy{{{*/
+Object* IntInput::copy() {
+
+	return new IntInput(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*IntInput management*/
+/*FUNCTION IntInput::Echo {{{*/
+void IntInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION IntInput::InstanceEnum{{{*/
+int IntInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION IntInput::SpawnTriaInput{{{*/
+Input* IntInput::SpawnTriaInput(int* indices){
+
+	/*output*/
+	IntInput* outinput=new IntInput();
+
+	/*only copy current value*/
+	outinput->enum_type=this->enum_type;
+	outinput->value=this->value;
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+/*FUNCTION IntInput::SpawnResult{{{*/
+ElementResult* IntInput::SpawnResult(int step, IssmDouble time){
+
+	_error_("not supported yet!");
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION IntInput::GetInputValue(bool* pvalue) {{{*/
+void IntInput::GetInputValue(bool* pvalue){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(int* pvalue){{{*/
+void IntInput::GetInputValue(int* pvalue){
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue){{{*/
+void IntInput::GetInputValue(IssmDouble* pvalue){
+	_error_("IntInput cannot return a IssmDouble in parallel");
+}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void IntInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void IntInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::ChangeEnum{{{*/
+void IntInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION IntInput::SquareMin{{{*/
+void IntInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
+
+	/*square min of an integer is the square of the integer itself: */
+	*psquaremin=pow((IssmDouble)value,2);
+}
+/*}}}*/
+/*FUNCTION IntInput::Scale{{{*/
+void IntInput::Scale(IssmDouble scale_factor){
+	IssmDouble dvalue=(IssmDouble)value*scale_factor;
+	value=reCast<int>(dvalue);
+}
+/*}}}*/
+/*FUNCTION IntInput::AXPY{{{*/
+void IntInput::AXPY(Input* xinput,IssmDouble scalar){
+
+	IssmDouble dvalue;
+	IntInput*  xintinput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	xintinput=(IntInput*)xinput;
+
+	/*Carry out the AXPY operation depending on type:*/
+	switch(xinput->ObjectEnum()){
+
+		case IntInputEnum:
+			dvalue=(IssmDouble)this->value+scalar*(IssmDouble)xintinput->value;
+			this->value=reCast<int>(dvalue);
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION IntInput::Constrain{{{*/
+void IntInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+
+	if(!xIsNan<IssmDouble>(cm_min)) if (this->value<cm_min)this->value=reCast<int>(cm_min);
+	if(!xIsNan<IssmDouble>(cm_max)) if (this->value>cm_max)this->value=reCast<int>(cm_max);
+
+}
+/*}}}*/
+/*FUNCTION IntInput::GetVectorFromInputs{{{*/
+void IntInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+
+	_error_("not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION IntInput::Configure{{{*/
+void IntInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/IntInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/IntInput.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/IntInput.h	(revision 15396)
@@ -0,0 +1,85 @@
+/*! \file IntInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _INTINPUT_H_
+#define _INTINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class GaussTria;
+class GaussPenta;
+/*}}}*/
+
+class IntInput: public Input{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int    enum_type;
+		IssmInt value;
+
+		/*IntInput constructors, destructors: {{{*/
+		IntInput();
+		IntInput(int enum_type,IssmInt value);
+		~IntInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*IntInput management: {{{*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		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);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		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);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		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){_error_("not implemented yet");};
+		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 ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		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){_error_("InfinityNorm not implemented for integers");};
+		IssmDouble Max(void){_error_("Max not implemented for integers");};
+		IssmDouble MaxAbs(void){_error_("Max not implemented for integers");};
+		IssmDouble Min(void){_error_("Min not implemented for integers");};
+		IssmDouble MinAbs(void){_error_("Min not implemented for integers");};
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		/*}}}*/
+
+};
+#endif  /* _INTINPUT_H */
Index: /issm/trunk/src/c/classes/Inputs/PentaP1Input.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaP1Input.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/PentaP1Input.cpp	(revision 15396)
@@ -0,0 +1,600 @@
+/*!\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: /issm/trunk/src/c/classes/Inputs/PentaP1Input.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaP1Input.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/PentaP1Input.h	(revision 15396)
@@ -0,0 +1,87 @@
+/*! \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 15396)
+++ /issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 15396)
@@ -0,0 +1,536 @@
+/*!\file TransientInput.c
+ * \brief: implementation of the TransientInput 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"
+/*}}}*/
+
+/*TransientInput constructors and destructor*/
+/*FUNCTION TransientInput::TransientInput(){{{*/
+TransientInput::TransientInput(){
+
+	enum_type=UNDEF;
+	inputs=NULL;
+	this->numtimesteps=0;
+	this->parameters=NULL;
+	this->timesteps=NULL;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::TransientInput(int in_enum_type){{{*/
+TransientInput::TransientInput(int in_enum_type)
+{
+	/*Set Enum*/
+	enum_type=in_enum_type;
+
+	/*Allocate values and timesteps, and copy: */
+	this->numtimesteps=0;
+	this->timesteps=NULL;
+	inputs = new Inputs();
+	this->parameters=NULL;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::~TransientInput{{{*/
+TransientInput::~TransientInput(){
+	xDelete(this->timesteps);
+	this->timesteps=NULL;
+	this->numtimesteps=0;
+	parameters=NULL;
+	delete this->inputs;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION TransientInput::Echo {{{*/
+void TransientInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION TransientInput::DeepEcho{{{*/
+void TransientInput::DeepEcho(void){
+
+	int i;
+
+	_printf_("TransientInput:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   numtimesteps: " << this->numtimesteps << "\n");
+	_printf_("---inputs: \n"); 
+	for(i=0;i<this->numtimesteps;i++){
+		_printf_("   time: " << this->timesteps[i] << "  \n");
+		((Input*)this->inputs->GetObjectByOffset(i))->Echo();
+	}
+}
+/*}}}*/
+/*FUNCTION TransientInput::Id{{{*/
+int    TransientInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TransientInput::ObjectEnum{{{*/
+int TransientInput::ObjectEnum(void){
+
+	return TransientInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::copy{{{*/
+Object* TransientInput::copy() {
+
+	TransientInput* output=NULL;
+
+	output = new TransientInput();
+	output->enum_type=this->enum_type;
+	output->numtimesteps=this->numtimesteps;
+	output->timesteps=xNew<IssmDouble>(this->numtimesteps);
+        xMemCpy(output->timesteps,this->timesteps,this->numtimesteps);
+	output->inputs=(Inputs*)this->inputs->Copy();
+	output->parameters=this->parameters;
+
+	return output;
+
+}
+/*}}}*/
+
+/*TransientInput management*/
+/*FUNCTION TransientInput::InstanceEnum{{{*/
+int TransientInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::SpawnTriaInput{{{*/
+Input* TransientInput::SpawnTriaInput(int* indices){
+
+	/*output*/
+	TransientInput* outinput=NULL;
+
+	/*Create new Transientinput (copy of current input)*/
+	outinput=new TransientInput();
+	outinput->enum_type=this->enum_type;
+	outinput->numtimesteps=this->numtimesteps;
+	outinput->timesteps=xNew<IssmDouble>(this->numtimesteps);
+	xMemCpy(outinput->timesteps,this->timesteps,this->numtimesteps);
+	outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(indices);
+	outinput->parameters=this->parameters;
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::SpawnResult{{{*/
+ElementResult* TransientInput::SpawnResult(int step, IssmDouble time){
+
+	ElementResult* elementresult=NULL;
+
+	/*Ok, we want to spawn an ElementResult. We have the time, just get 
+	 *the correct values: */
+	Input* input=GetTimeInput(time);
+
+	elementresult=input->SpawnResult(step,time);
+
+   delete input;
+
+	return elementresult;
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION TransientInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void TransientInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	this->parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void TransientInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	this->parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){{{*/
+void TransientInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){{{*/
+void TransientInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void TransientInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussTria* gauss){
+
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputDerivativeValue(p,xyz_list,gauss);
+
+	delete input;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::ChangeEnum{{{*/
+void TransientInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputAverage{{{*/
+void TransientInput::GetInputAverage(IssmDouble* pvalue){
+
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputAverage(pvalue);
+
+	delete input;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputAllTimeAverages{{{*/
+void TransientInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){
+
+	int i;
+	IssmDouble* times=NULL;
+	IssmDouble* values=NULL;
+
+	/*allocate: */
+	times=xNew<IssmDouble>(this->numtimesteps);
+	values=xNew<IssmDouble>(this->numtimesteps);
+
+	for(i=0;i<numtimesteps;i++){
+		Input* input=(Input*)this->inputs->GetObjectByOffset(i);
+		input->GetInputAverage(values+i);
+		times[i]=this->timesteps[i];
+	}
+
+	*pvalues=values;
+	*ptimes=times;
+	*pnumtimes=numtimesteps;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputUpToCurrentTimeAverages{{{*/
+void TransientInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){
+
+	int i;
+	IssmDouble* times=NULL;
+	IssmDouble* values=NULL;
+	int numsteps;
+	int count;
+	bool iscurrenttime_included=false;
+
+	/*Figure out how many time steps we are going to return: */
+	numsteps=0;
+	for(i=0;i<numtimesteps;i++){
+		if(this->timesteps[i]==currenttime)iscurrenttime_included=true;
+		if (this->timesteps[i]>currenttime)break;
+		else numsteps++;
+	}
+	if(iscurrenttime_included==false)numsteps++;
+
+	/*allocate: */
+	times=xNew<IssmDouble>(numsteps);
+	values=xNew<IssmDouble>(numsteps);
+
+	for(i=0;i<numsteps;i++){
+
+		if((iscurrenttime_included==false) && (i==(numsteps-1))){
+
+			/*Retrieve interpolated values for current time step: */
+			Input* input=GetTimeInput(currenttime);
+			input->GetInputAverage(values+i);
+			times[i]=currenttime;
+		}
+		else{
+			Input* input=(Input*)this->inputs->GetObjectByOffset(i);
+			input->GetInputAverage(values+i);
+			times[i]=this->timesteps[i];
+		}
+	}
+
+	*pvalues=values;
+	*ptimes=times;
+	*pnumtimes=numtimesteps;
+}
+/*}}}*/
+
+/*Intermediary*/
+/*FUNCTION TransientInput::AddTimeInput{{{*/
+void TransientInput::AddTimeInput(Input* input,IssmDouble time){
+
+	/*insert values at time step: */
+	if (this->numtimesteps>0 && time<=this->timesteps[this->numtimesteps-1]) _error_("timestep values must increase sequentially");
+
+	//copy timesteps, add the new time, delete previous timesteps, and add the new input: inputs->AddObject(input);
+	IssmDouble* old_timesteps=NULL;
+
+	if (this->numtimesteps > 0){
+		old_timesteps=xNew<IssmDouble>(this->numtimesteps);
+		xMemCpy(old_timesteps,this->timesteps,this->numtimesteps);
+		xDelete(this->timesteps);
+	}
+
+	this->numtimesteps=this->numtimesteps+1;
+	this->timesteps=xNew<IssmDouble>(this->numtimesteps);
+
+	if (this->numtimesteps > 1){
+		xMemCpy(this->timesteps,old_timesteps,this->numtimesteps-1);
+		xDelete(old_timesteps);
+	}
+
+	/*go ahead and plug: */
+	this->timesteps[this->numtimesteps-1]=time;
+	inputs->AddObject(input);
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::Extrude{{{*/
+void TransientInput::Extrude(void){
+
+	for(int i=0;i<this->numtimesteps;i++){
+		((Input*)this->inputs->GetObjectByOffset(i))->Extrude();
+	}
+}
+/*}}}*/
+/*FUNCTION TransientInput::SquareMin{{{*/
+void TransientInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
+
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->SquareMin(psquaremin,parameters);
+
+	delete input;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::InfinityNorm{{{*/
+IssmDouble TransientInput::InfinityNorm(void){
+
+	IssmDouble time;
+	IssmDouble infnorm;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	infnorm=input->InfinityNorm();
+
+	/*Clean-up and return*/
+	delete input;
+	return infnorm;
+}
+/*}}}*/
+/*FUNCTION TransientInput::Max{{{*/
+IssmDouble TransientInput::Max(void){
+
+	IssmDouble time;
+	IssmDouble max;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	max=input->Max();
+
+	delete input;
+
+	return max;
+}
+/*}}}*/
+/*FUNCTION TransientInput::MaxAbs{{{*/
+IssmDouble TransientInput::MaxAbs(void){
+
+	IssmDouble time;
+	IssmDouble maxabs;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	maxabs=input->MaxAbs();
+
+	/*Clean-up and return*/
+	delete input;
+	return maxabs;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::Min{{{*/
+IssmDouble TransientInput::Min(void){
+
+	IssmDouble time;
+	IssmDouble min;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	min=input->Min();
+
+	/*Clean-up and return*/
+	delete input;
+	return min;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::MinAbs{{{*/
+IssmDouble TransientInput::MinAbs(void){
+
+	IssmDouble time;
+	IssmDouble minabs;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	minabs=input->MinAbs();
+
+	/*Clean-up and return*/
+	delete input;
+	return minabs;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetVectorFromInputs{{{*/
+void TransientInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetVectorFromInputs(vector,doflist);
+
+	delete input;
+
+} /*}}}*/
+/*FUNCTION TransientInput::GetTimeInput{{{*/
+Input* TransientInput::GetTimeInput(IssmDouble intime){
+
+	IssmDouble deltat;
+	IssmDouble alpha1,alpha2;
+	int        found;
+	int        offset;
+
+	Input *input  = NULL;
+	Input *input1 = NULL;
+	Input *input2 = NULL;
+
+	/*go through the timesteps, and figure out which interval we 
+	 *fall within. Then interpolate the values on this interval: */
+	found=binary_search(&offset,intime,this->timesteps,this->numtimesteps);
+	if(!found) _error_("Input not found (is TransientInput sorted ?)");
+
+	if (offset==-1){
+		/*get values for the first time: */
+		_assert_(intime<this->timesteps[0]);
+		input=(Input*)((Input*)this->inputs->GetObjectByOffset(0))->copy();
+	}
+	else if(offset==(this->numtimesteps-1)){
+		/*get values for the last time: */
+		_assert_(intime>=this->timesteps[offset]);
+		input=(Input*)((Input*)this->inputs->GetObjectByOffset(offset))->copy();
+	}
+	else{
+		/*get values between two times [offset:offset+1[, Interpolate linearly*/
+		_assert_(intime>=this->timesteps[offset] && intime<this->timesteps[offset+1]);
+		deltat=this->timesteps[offset+1]-this->timesteps[offset];
+		alpha2=(intime-this->timesteps[offset])/deltat;
+		alpha1=(1.0-alpha2);
+
+		input1=(Input*)this->inputs->GetObjectByOffset(offset); 
+		input2=(Input*)this->inputs->GetObjectByOffset(offset+1);
+
+		input=(Input*)input1->copy();
+		input->Scale(alpha1);
+		input->AXPY(input2,alpha2);
+	}
+
+	/*Assign output pointer*/
+	return input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::Configure{{{*/
+void TransientInput::Configure(Parameters* parameters){
+	this->parameters=parameters;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/TransientInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TransientInput.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/TransientInput.h	(revision 15396)
@@ -0,0 +1,90 @@
+/*! \file TransientInput.h 
+ *  \brief: header file for transientinput object
+ */
+
+#ifndef _TRANSIENTINPUT_H_
+#define _TRANSIENTINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+class GaussTria;
+class Parameters;
+class GaussPenta;
+/*}}}*/
+
+class TransientInput: public Input{
+
+	public:
+		int         enum_type;
+		int         numtimesteps;
+		Inputs     *inputs;
+		IssmDouble *timesteps;
+		Parameters *parameters;     //to find current time.
+
+		/*TransientInput constructors, destructors: {{{*/
+		TransientInput();
+		TransientInput(int enum_type);
+		~TransientInput();
+		void AddTimeInput(Input* input,IssmDouble time);
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		int   Id();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*TransientInput management: {{{*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* forcingB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* forcingB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* forcingB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		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);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time);
+		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);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes);
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime);
+		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){_error_("not implemented yet");};
+		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 ChangeEnum(int newenumtype);
+
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xforcing,IssmDouble scalar){_error_("not implemented yet");};
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void);
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_forcing){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		void GetTimeValues(IssmDouble* values,IssmDouble time){_error_("not implemented yet");};
+		Input* GetTimeInput(IssmDouble time);
+		/*}}}*/
+
+};
+#endif  /* _TRANSIENTINPUT_H */
Index: /issm/trunk/src/c/classes/Inputs/TriaInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TriaInput.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/TriaInput.cpp	(revision 15396)
@@ -0,0 +1,444 @@
+/*!\file TriaInput.c
+ * \brief: implementation of the TriaInput 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"
+
+/*TriaInput constructors and destructor*/
+/*FUNCTION TriaInput::TriaInput(){{{*/
+TriaInput::TriaInput(){
+	values = NULL;
+}
+/*}}}*/
+/*FUNCTION TriaInput::TriaInput(int in_enum_type,IssmDouble* invalues,element_type_in){{{*/
+TriaInput::TriaInput(int in_enum_type,IssmDouble* in_values,int element_type_in)
+	:TriaRef(1)
+{
+
+	/*Set TriaRef*/
+	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 TriaInput::~TriaInput(){{{*/
+TriaInput::~TriaInput(){
+	xDelete<IssmDouble>(this->values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION TriaInput::Echo {{{*/
+void TriaInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION TriaInput::DeepEcho{{{*/
+void TriaInput::DeepEcho(void){
+
+	_printf_("TriaInput:\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 TriaInput::Id{{{*/
+int    TriaInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TriaInput::ObjectEnum{{{*/
+int TriaInput::ObjectEnum(void){
+
+	return TriaInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION TriaInput::copy{{{*/
+Object* TriaInput::copy() {
+
+	return new TriaInput(this->enum_type,this->values,this->element_type);
+
+}
+/*}}}*/
+
+/*TriaInput management*/
+/*FUNCTION TriaInput::InstanceEnum{{{*/
+int TriaInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION TriaInput::SpawnTriaInput{{{*/
+Input* TriaInput::SpawnTriaInput(int* indices){
+
+	/*output*/
+	TriaInput* outinput=NULL;
+
+	/*Create new Tria input (copy of current input)*/
+	outinput=new TriaInput(this->enum_type,&this->values[0],this->element_type);
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TriaInput::SpawnResult{{{*/
+ElementResult* TriaInput::SpawnResult(int step, IssmDouble time){
+
+	return new TriaP1ElementResult(this->enum_type,this->values,step,time);
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION TriaInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void TriaInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){
+
+	/*Call TriaRef function*/
+	TriaRef::GetInputValue(pvalue,&values[0],gauss);
+
+}
+/*}}}*/
+/*FUNCTION TriaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void TriaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussTria* gauss){
+
+	/*Call TriaRef function*/
+	TriaRef::GetInputDerivativeValue(p,&values[0],xyz_list,gauss);
+}
+/*}}}*/
+/*FUNCTION TriaInput::GetVxStrainRate2d{{{*/
+void TriaInput::GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){
+
+	/*Intermediary*/
+	int numnodes=this->NumberofNodes();
+	IssmDouble* B=xNew<IssmDouble>(numnodes*(NDOF2*numnodes));
+	IssmDouble* velocity=xNew<IssmDouble>(numnodes*NDOF2);
+
+	/*Get B matrix: */
+	GetBMacAyeal(&B[0],xyz_list,gauss);
+
+	/*Here, we are computing the strain rate of (vx,0)*/
+	for(int i=0;i<numnodes;i++){
+		velocity[2*i+0]=this->values[i];
+		velocity[2*i+1]=0.;
+	}
+	/*Get epsilon(vx) = B*velocity*/
+	MatrixMultiply(&B[0],numnodes,NDOF2*numnodes,0,
+				&velocity[0],NDOF2*numnodes,1,0,
+				epsilonvx,0);
+
+	/*clean up*/
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(velocity);
+}
+/*}}}*/
+/*FUNCTION TriaInput::GetVyStrainRate2d{{{*/
+void TriaInput::GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){
+
+	/*Intermediary*/
+	int numnodes=this->NumberofNodes();
+	IssmDouble* B=xNew<IssmDouble>(numnodes*(NDOF2*numnodes));
+	IssmDouble* velocity=xNew<IssmDouble>(numnodes*NDOF2);
+
+	/*Get B matrix: */
+	GetBMacAyeal(&B[0],xyz_list,gauss);
+
+	/*Here, we are computing the strain rate of (0,vy)*/
+	for(int i=0;i<numnodes;i++){
+		velocity[2*i+0]=0.;
+		velocity[2*i+1]=this->values[i];
+	}
+	/*Get epsilon(vy) = B*velocity*/
+	MatrixMultiply(&B[0],numnodes,NDOF2*numnodes,0,
+				&velocity[0],NDOF2*numnodes,1,0,
+				epsilonvy,0);
+
+	/*clean up*/
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(velocity);
+}
+/*}}}*/
+/*FUNCTION TriaInput::ChangeEnum{{{*/
+void TriaInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION TriaInput::GetInputAverage{{{*/
+void TriaInput::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;
+}
+/*}}}*/
+/*FUNCTION TriaInput::GetInputAllTimeAverages{{{*/
+void TriaInput::GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){
+
+	IssmDouble* outvalues=NULL;
+	IssmDouble* times=NULL;
+	int         numtimes;
+
+	/*this is not a transient forcing, so we only have 1 value, steady state: */
+	numtimes=1;
+	outvalues=xNew<IssmDouble>(1);
+	times=xNew<IssmDouble>(1);
+
+	this->GetInputAverage(&outvalues[0]);
+	times[0]=0.; /*we don't have a time*/
+
+	*pvalues=outvalues;
+	*ptimes=times;
+	*pnumtimes=numtimes;
+}
+/*}}}*/
+/*FUNCTION TriaInput::GetInputUpToCurrentTimeAverages{{{*/
+void TriaInput::GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){
+
+	IssmDouble* outvalues=NULL;
+	IssmDouble* times=NULL;
+	int         numtimes;
+
+	/*this is not a transient forcing, so we only have 1 value, steady state: */
+	numtimes=1;
+	outvalues=xNew<IssmDouble>(1);
+	times=xNew<IssmDouble>(1);
+
+	this->GetInputAverage(&outvalues[0]);
+	times[0]=currenttime; /*we don't have a time*/
+
+	*pvalues=outvalues;
+	*ptimes=times;
+	*pnumtimes=numtimes;
+}
+/*}}}*/
+
+/*Intermediary*/
+/*FUNCTION TriaInput::SquareMin{{{*/
+void TriaInput::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 TriaInput::ContrainMin{{{*/
+void TriaInput::ConstrainMin(IssmDouble minimum){
+
+	const int numnodes = this->NumberofNodes();
+	for(int i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
+}
+/*}}}*/
+/*FUNCTION TriaInput::InfinityNorm{{{*/
+IssmDouble TriaInput::InfinityNorm(void){
+
+	/*Output*/
+	IssmDouble norm=0;
+	const int numnodes=this->NumberofNodes();
+
+	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
+	return norm;
+}
+/*}}}*/
+/*FUNCTION TriaInput::Max{{{*/
+IssmDouble TriaInput::Max(void){
+
+	const 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 TriaInput::MaxAbs{{{*/
+IssmDouble TriaInput::MaxAbs(void){
+
+	const 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 TriaInput::Min{{{*/
+IssmDouble TriaInput::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 TriaInput::MinAbs{{{*/
+IssmDouble TriaInput::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 TriaInput::Scale{{{*/
+void TriaInput::Scale(IssmDouble scale_factor){
+
+	const int numnodes=this->NumberofNodes();
+
+	for(int i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
+}
+/*}}}*/
+/*FUNCTION TriaInput::ArtificialNoise{{{*/
+void TriaInput::ArtificialNoise(IssmDouble min,IssmDouble max){
+
+	int i;
+	const int numnodes=this->NumberofNodes();
+	IssmDouble noise;
+
+	/*Compute random number between bounds:
+	 * rand() outputs an integer in [0 RAND_MAX]
+	 * (IssmDouble)rand()/RAND_MAX is in [0 1]
+	 */
+	 noise=min+(max-min)*(IssmDouble)rand()/RAND_MAX;
+
+	for(i=0;i<numnodes;i++)values[i]=values[i]+noise;
+}
+/*}}}*/
+/*FUNCTION TriaInput::AXPY{{{*/
+void TriaInput::AXPY(Input* xinput,IssmDouble scalar){
+
+	int i;
+	const int numnodes=this->NumberofNodes();
+	TriaInput*  xtriavertexinput=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()));
+
+	/*Carry out the AXPY operation depending on type:*/
+	for(i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*xtriavertexinput->values[i];
+
+}
+/*}}}*/
+/*FUNCTION TriaInput::Constrain{{{*/
+void TriaInput::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 TriaInput::GetVectorFromInputs{{{*/
+void TriaInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+
+	const int numnodes=this->NumberofNodes();
+	vector->SetValues(numnodes,doflist,this->values,INS_VAL);
+
+} /*}}}*/
+/*FUNCTION TriaInput::PointwiseMin{{{*/
+Input* TriaInput::PointwiseMin(Input* inputB){
+
+	/*Ouput*/
+	TriaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	int         i;
+	TriaInput  *xinputB   = NULL;
+	const int   numnodes  = this->NumberofNodes();
+	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
+
+	/*Check that inputB is of the same type*/
+	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()));
+
+	/*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 Tria vertex input (copy of current input)*/
+	outinput=new TriaInput(this->enum_type,&minvalues[0],this->element_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(minvalues);
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TriaInput::PointwiseMax{{{*/
+Input* TriaInput::PointwiseMax(Input* inputB){
+
+	/*Ouput*/
+	TriaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	int         i;
+	TriaInput  *xinputB   = NULL;
+	const int   numnodes  = this->NumberofNodes();
+	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
+
+	/*Check that inputB is of the same type*/
+	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()));
+
+	/*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 Tria vertex input (copy of current input)*/
+	outinput=new TriaInput(this->enum_type,&maxvalues[0],this->element_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(maxvalues);
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TriaInput::Configure{{{*/
+void TriaInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/TriaInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 15396)
@@ -0,0 +1,85 @@
+/*! \file TriaInput.h 
+ *  \brief: header file for TriaInput object
+ */
+
+#ifndef _TRIAINPUT_H_
+#define _TRIAINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../Elements/TriaRef.h"
+class GaussTria;
+class GaussPenta;
+/*}}}*/
+
+class TriaInput: public Input,public TriaRef{
+
+	public:
+		int         enum_type;
+		IssmDouble* values;
+
+		/*TriaInput constructors, destructors*/
+		TriaInput();
+		TriaInput(int enum_type,IssmDouble* values,int element_type_in);
+		~TriaInput();
+
+		/*Object virtual functions definitions*/
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+
+		/*TriaInput management:*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		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);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not implemented yet");};
+		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);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes);
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime);
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss);
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss);
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		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 ChangeEnum(int newenumtype);
+
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum);
+		void Scale(IssmDouble scale_factor);
+		void ArtificialNoise(IssmDouble min,IssmDouble max);
+		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){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		/*}}}*/
+
+};
+#endif  /* _TRIAINPUT_H */
Index: /issm/trunk/src/c/classes/IoModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/IoModel.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/IoModel.cpp	(revision 15396)
@@ -16,8 +16,6 @@
 
 #include "./classes.h"
-#include "../io/io.h"
-#include "../Container/Parameters.h"
+#include "../shared/io/io.h"
 #include "../shared/shared.h"
-#include "../include/include.h"
 
 /*FUNCTION IoModel::IoModel(){{{*/
@@ -26,4 +24,5 @@
 	this->data=NULL;
 	this->independents=NULL;
+	this->independent_objects=NULL;
 	this->constants=NULL;
 
@@ -31,4 +30,5 @@
 	this->my_nodes=NULL;
 	this->my_vertices=NULL;
+
 	this->singlenodetoelementconnectivity=NULL;
 	this->numbernodetoelementconnectivity=NULL;
@@ -65,4 +65,5 @@
 	this->my_nodes=NULL;
 	this->my_vertices=NULL;
+
 	this->singlenodetoelementconnectivity=NULL;
 	this->numbernodetoelementconnectivity=NULL;
@@ -83,5 +84,5 @@
 		for(int i=0;i<MaximumNumberOfEnums;i++){
 			if(this->data[i]){
-				_pprintLine_("Info: previous pointer of " << EnumToStringx(i) << " has not been freed (DeleteData has not been called)");
+				_printf0_("Info: previous pointer of " << EnumToStringx(i) << " has not been freed (DeleteData has not been called)\n");
 			}
 		}
@@ -124,18 +125,18 @@
 		else{
 			if(record_enum!=MaximumNumberOfEnums){
-				_printLine_("");
-				_printLine_("=========================================================================");
-				_printLine_(" Enums in marshalled file are not compatible with compiled code          ");
-				_printLine_("                                                                         ");
-				_printLine_("   * If you are running ISSM on a remote cluster:                        ");
-				_printLine_("     make sure that you are using the same version of ISSM on your local ");
-				_printLine_("     machine and remote cluster (you might need to run svn update)       ");
-				_printLine_("   * If you are running ISSM on your local machine:                      ");
-				_printLine_("     make sure that all the code is compiled (modules and executables)   ");
-				_printLine_("   * If you are a developer and just added a new Enum:                   ");
-				_printLine_("     you might need to run ./Synchronize.sh in src/c/EnumDefinitions     ");
-				_printLine_("     and recompile                                                       ");
-				_printLine_("=========================================================================");
-				_printLine_("");
+				_printf0_("\n");
+				_printf0_("=========================================================================\n");
+				_printf0_(" Enums in marshalled file are not compatible with compiled code          \n");
+				_printf0_("                                                                         \n");
+				_printf0_("   * If you are running ISSM on a remote cluster:                        \n");
+				_printf0_("     make sure that you are using the same version of ISSM on your local \n");
+				_printf0_("     machine and remote cluster (you might need to run svn update)       \n");
+				_printf0_("   * If you are running ISSM on your local machine:                      \n");
+				_printf0_("     make sure that all the code is compiled (modules and executables)   \n");
+				_printf0_("   * If you are a developer and just added a new Enum:                   \n");
+				_printf0_("     you might need to run ./Synchronize.sh in src/c/EnumDefinitions     \n");
+				_printf0_("     and recompile                                                       \n");
+				_printf0_("=========================================================================\n");
+				_printf0_("\n");
 				_error_("Enums not consistent (See error message above)");
 			}
@@ -204,14 +205,13 @@
 void IoModel::DeclareIndependents(void){
 
-	int         i;
-	bool        autodiff                = false;
-	int         num_independent_objects;
+	int  i;
+	bool autodiff = false;
+	int  num_independent_objects;
 
 	int *names = NULL;
 	int *types = NULL;
 
-	int         numberofvertices;
-	int         dummy;
-	bool        keep=false;
+	int  dummy;
+	bool keep=false;
 
 	/*Initialize array detecting whether data[i] is an independent AD mode variable: */
@@ -222,15 +222,11 @@
 	if(autodiff){
 
-		this->FetchData(&numberofvertices,MeshNumberofverticesEnum);
-
 		#ifdef _HAVE_ADOLC_
-
-		/*Start trace: {{{*/
+		/*Start trace*/
 		this->FetchData(&keep,AutodiffKeepEnum);
 		if(keep)trace_on(1,1);
 		else    trace_on(1);
 
-		/*}}}*/
-		/*build dataset made of independent objects: {{{*/
+		/*build dataset made of independent objects:*/
 		this->independent_objects=new DataSet();
 		this->FetchData(&num_independent_objects,AutodiffNumIndependentObjectsEnum);
@@ -244,5 +240,5 @@
 
 				IndependentObject* independent_object=NULL;
-				independent_object=new IndependentObject(names[i],types[i],numberofvertices);
+				independent_object=new IndependentObject(names[i],types[i]);
 
 				/*add to independent_objects dataset:*/
@@ -254,6 +250,5 @@
 			xDelete<int>(names);
 			xDelete<int>(types);
-		} /*}}}*/
-
+		}
 		#else
 		/*if we asked for AD computations, we have a problem!: */
@@ -337,6 +332,6 @@
 
 				/* Read the record length and the data type code: */
-				fread(&record_length,sizeof(int),1,this->fid);
-				fread(&record_code,sizeof(int),1,this->fid);
+				if(fread(&record_length,sizeof(int),1,this->fid)!=1) _error_("Cound not read record_length");
+				if(fread(&record_code  ,sizeof(int),1,this->fid)!=1) _error_("Cound not read record_code");
 
 				#ifdef _HAVE_MPI_
@@ -685,5 +680,4 @@
 	int*    integer_matrix=NULL;
 	int code=0;
-	int vector_type=0;
 
 	/*recover my_rank:*/
@@ -691,5 +685,5 @@
 
 	/*Set file pointer to beginning of the data: */
-	fid=this->SetFilePointerToData(&code,&vector_type,data_enum);
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
 
 	if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
@@ -759,5 +753,4 @@
 	IssmPDouble* matrix=NULL;
 	int code=0;
-	int vector_type=0;
 
 	/*recover my_rank:*/
@@ -765,5 +758,5 @@
 
 	/*Set file pointer to beginning of the data: */
-	fid=this->SetFilePointerToData(&code,&vector_type,data_enum);
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
 	if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
 
@@ -1266,6 +1259,6 @@
 
 	int my_rank;
-	int        lastindex,index;
-	int        record_length;
+	int lastindex,index;
+	int record_length;
 
 	/*recover my_rank:*/
@@ -1287,5 +1280,5 @@
 
 			/*read the record length, and use it to skip this record: */
-			fread(&record_length,sizeof(int),1,fid);
+			if(fread(&record_length,sizeof(int),1,fid)!=1) _error_("Could not read record_length");
 			fseek(fid,record_length,SEEK_CUR);
 			lastindex=index;
@@ -1334,8 +1327,10 @@
 				/*Ok, we have found the correct string. Pass the record length, and read data type code: */
 				fseek(fid,sizeof(int),SEEK_CUR);
-				fread(&record_code,sizeof(int),1,fid);
+				if(fread(&record_code,sizeof(int),1,fid)!=1) _error_("Could not read record_code");
 
 				/*if record_code points to a vector, get its type (nodal or elementary): */
-				if(5<=record_code && record_code<=7)fread(&vector_type,sizeof(int),1,fid);
+				if(5<=record_code && record_code<=7){
+					if(fread(&vector_type,sizeof(int),1,fid)!=1) _error_("Could not read vector_type");
+				}
 				found=1;
 				break;
@@ -1343,5 +1338,5 @@
 			else{
 				/*This is not the correct string, read the record length, and use it to skip this record: */
-				fread(&record_length,sizeof(int),1,fid);
+				if(fread(&record_length,sizeof(int),1,fid)!=1) _error_("Could not read record_length");
 				/*skip: */
 				fseek(fid,record_length,SEEK_CUR);
Index: /issm/trunk/src/c/classes/IoModel.h
===================================================================
--- /issm/trunk/src/c/classes/IoModel.h	(revision 15395)
+++ /issm/trunk/src/c/classes/IoModel.h	(revision 15396)
@@ -8,6 +8,5 @@
 #define _IOMODEL_H
 
-#include "../include/include.h"
-#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/Enum/Enum.h"
 
 class Parameters;
@@ -24,20 +23,24 @@
 		IssmDouble **data;   //this dataset holds temporary data, memory intensive.
 
-		/*This data needs to stay memory resident at all time, even if it's memory intensive: */
-		FILE *fid;                               //pointer to input file
+		/*pointer to input file*/
+		FILE *fid;
+
+		/*Partitioning*/
 		bool *my_elements;
 		bool *my_nodes;
 		int  *my_vertices;
+
+		/*Connectivity tables*/
 		int  *singlenodetoelementconnectivity;
 		int  *numbernodetoelementconnectivity;
 
 		/*Data to synchronize through low level object drivers: */
-		int nodecounter;         //keep track of how many nodes are being created in each analysis type
-		int loadcounter;         //keep track of how many loads are being created in each analysis type
-		int constraintcounter;   //keep track of how many constraints are being created in each analysis type
+		int nodecounter;         //keep track of how many nodes are being created in each analysis
+		int loadcounter;         //keep track of how many loads are being created in each analysis
+		int constraintcounter;   //keep track of how many constraints are being created in each analysis
 
 		/*for AD mode: to keep track of our independent variables we fetch:*/
-		bool* independents;
-		DataSet* independent_objects;
+		bool    *independents;
+		DataSet *independent_objects;
 
 		/*Methods*/
@@ -67,5 +70,5 @@
 		void        FetchData(Option **poption,int data_enum);
 		void        FetchData(int num,...);
-		void        FetchDataToInput(Elements* elements,int vector_enum,int default_vector_enum=NoneEnum,IssmDouble default_value=0);
+		void        FetchDataToInput(Elements* elements,int vector_enum,int default_vector_enum=NoneEnum,IssmDouble default_value=0.);
 		void        LastIndex(int *pindex);
 		FILE*       SetFilePointerToData(int* pcode,int* pvector_type, int data_enum);
Index: sm/trunk/src/c/classes/IssmComm.cpp
===================================================================
--- /issm/trunk/src/c/classes/IssmComm.cpp	(revision 15395)
+++ 	(revision )
@@ -1,62 +1,0 @@
-/*! \file IssmComm.cpp
- * \brief  file containing the methods for IssmComm.h
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "./IssmComm.h"
-#include "../include/types.h"
-#include "../include/macros.h"
-#include "../shared/Exceptions/exceptions.h"
-
-void IssmComm::SetComm(COMM incomm){ /*{{{*/
-
-	/*A comm is provided, we are running in parallel (this is not a module)*/
-	parallel = true;
-	comm     = incomm;
-
-}/*}}}*/
-void IssmComm::SetComm(void){ /*{{{*/
-
-	/*no comm provided, This is a matlab/python module*/
-	parallel = false;
-
-	/*No need to initialise comm*/
-
-}/*}}}*/
-COMM IssmComm::GetComm(){  /*{{{*/
-	if(!parallel) _error_("Cannot return comm in serial mode");
-	return comm;
-}/*}}}*/
-int IssmComm::GetRank(){  /*{{{*/
-
-	int my_rank = 0;
-	
-	/*for matlab and python modules*/
-	if(!parallel) return my_rank;
-
-	#ifdef _HAVE_MPI_
-	MPI_Comm_rank(comm,&my_rank);
-	#endif
-
-	return my_rank;
-
-}/*}}}*/
-int IssmComm::GetSize(){  /*{{{*/
-
-	int size = 1;
-
-	/*for matlab and python modules*/
-	if(!parallel) return size;
-
-	#ifdef _HAVE_MPI_
-	MPI_Comm_size(comm,&size);
-	#endif
-
-	return size;
-
-}/*}}}*/
Index: sm/trunk/src/c/classes/IssmComm.h
===================================================================
--- /issm/trunk/src/c/classes/IssmComm.h	(revision 15395)
+++ 	(revision )
@@ -1,33 +1,0 @@
-/* \file IssmComm.h
- * \brief  create a class with a static comm, and static methods to access it
- * This is a way of protecting access to the communicator.
- */
-
-#ifndef _ISSM_COMM_H
-#define _ISSM_COMM_H
-
-/*{{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "../include/types.h"
-/*}}}*/
-
-class IssmComm {
-
-	private:
-		static COMM comm;
-		static bool parallel;
-
-	public:
-		static void SetComm(COMM incomm);
-		static void SetComm(void);
-		static COMM GetComm(void);
-		static int GetRank(void);
-		static int GetSize(void);
-};
-
-#endif  /* _ISSM_COMM_H */
Index: /issm/trunk/src/c/classes/Loads/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Loads/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,15 @@
+# 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: /issm/trunk/src/c/classes/Loads/Friction.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 15396)
@@ -0,0 +1,327 @@
+/*!\file Friction.c
+ * \brief: implementation of the Friction 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"
+/*}}}*/	
+
+/*Constructors/destructors*/
+/*FUNCTION Friction::Friction() {{{*/
+Friction::Friction(){
+	this->element_type=NULL;
+	this->inputs=NULL;
+	this->matpar=NULL;
+}
+/*}}}*/
+/*FUNCTION Friction::Friction(const char* element_type, Inputs* inputs,Matpar* matpar,int analysis_type){{{*/
+Friction::Friction(const char* element_type_in,Inputs* inputs_in,Matpar* matpar_in, int in_analysis_type){
+
+	this->analysis_type=in_analysis_type;
+	this->inputs=inputs_in;
+	this->element_type=xNew<char>(strlen(element_type_in)+1);
+	xMemCpy<char>(this->element_type,element_type_in,(strlen(element_type_in)+1));
+
+	this->matpar=matpar_in;
+}
+/*}}}*/
+/*FUNCTION Friction::~Friction() {{{*/
+Friction::~Friction(){
+	xDelete<char>(element_type);
+}
+/*}}}*/
+
+/*methods: */
+/*FUNCTION Friction::Echo {{{*/
+void Friction::Echo(void){
+	_printf_("Friction:\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   element_type: " << this->element_type << "\n");
+	inputs->Echo();
+	matpar->Echo();
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlpha2(IssmDouble* palpha2, GaussTria* gauss,int vxenum,int vyenum,int vzenum){{{*/
+void Friction::GetAlpha2(IssmDouble* palpha2, GaussTria* gauss,int vxenum,int vyenum,int vzenum){
+
+	/*This routine calculates the basal friction coefficient 
+	  alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
+
+	/*diverse: */
+	IssmDouble  r,s;
+	IssmDouble  drag_p, drag_q;
+	IssmDouble  gravity,rho_ice,rho_water;
+	IssmDouble  Neff;
+	IssmDouble  thickness,bed;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  drag_coefficient;
+	IssmDouble  alpha2;
+
+	/*Recover parameters: */
+	inputs->GetInputValue(&drag_p,FrictionPEnum);
+	inputs->GetInputValue(&drag_q,FrictionQEnum);
+	this->GetInputValue(&thickness, gauss,ThicknessEnum);
+	this->GetInputValue(&bed, gauss,BedEnum);
+	this->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+
+	/*Get material parameters: */
+	gravity=matpar->GetG();
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+
+	/*If effective pressure becomes negative, sliding becomes unstable (Paterson 4th edition p 148). This is because 
+	  the water pressure is so high, the ice sheet elevates over its ice bumps and slides. But the limit behaviour 
+	  for friction should be an ice shelf sliding (no basal drag). Therefore, for any effective pressure Neff < 0, we should 
+	  replace it by Neff=0 (ie, equival it to an ice shelf)*/
+	if (Neff<0)Neff=0;
+
+	if(strcmp(element_type,"2d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2));
+	}
+	else if (strcmp(element_type,"3d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		this->GetInputValue(&vz, gauss,vzenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
+	}
+	else _error_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+        if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha2 is Inf");
+
+	alpha2=pow(drag_coefficient,2)*pow(Neff,r)*pow(vmag,(s-1));
+	_assert_(!xIsNan<IssmDouble>(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlpha2(IssmDouble* palpha2, GaussPenta* gauss,int vxenum,int vyenum,int vzenum){{{*/
+void Friction::GetAlpha2(IssmDouble* palpha2, GaussPenta* gauss,int vxenum,int vyenum,int vzenum){
+
+	/*This routine calculates the basal friction coefficient 
+	  alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
+
+	/*diverse: */
+	IssmDouble  r,s;
+	IssmDouble  drag_p, drag_q;
+	IssmDouble  gravity,rho_ice,rho_water;
+	IssmDouble  Neff;
+	IssmDouble  thickness,bed;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  drag_coefficient;
+	IssmDouble  alpha2;
+
+	/*Recover parameters: */
+	inputs->GetInputValue(&drag_p,FrictionPEnum);
+	inputs->GetInputValue(&drag_q,FrictionQEnum);
+	this->GetInputValue(&thickness, gauss,ThicknessEnum);
+	this->GetInputValue(&bed, gauss,BedEnum);
+	this->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+
+	/*Get material parameters: */
+	gravity=matpar->GetG();
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+
+	/*If effective pressure becomes negative, sliding becomes unstable (Paterson 4th edition p 148). This is because 
+	  the water pressure is so high, the ice sheet elevates over its ice bumps and slides. But the limit behaviour 
+	  for friction should be an ice shelf sliding (no basal drag). Therefore, for any effective pressure Neff < 0, we should 
+	  replace it by Neff=0 (ie, equival it to an ice shelf)*/
+	if (Neff<0)Neff=0;
+
+	if(strcmp(element_type,"2d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2));
+	}
+	else if (strcmp(element_type,"3d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		this->GetInputValue(&vz, gauss,vzenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
+	}
+	else _error_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+
+	alpha2=pow(drag_coefficient,2)*pow(Neff,r)*pow(vmag,(s-1));
+	_assert_(!xIsNan<IssmDouble>(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlphaComplement(IssmDouble* palpha_complement, GaussTria* gauss,int vxenum,int vyenum,int vzenum) {{{*/
+void Friction::GetAlphaComplement(IssmDouble* palpha_complement, GaussTria* gauss,int vxenum,int vyenum,int vzenum){
+
+	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
+	 * FrictionGetAlphaComplement is used in control methods on drag, and it computes: 
+	 * alpha_complement= Neff ^r * vel ^s*/
+
+	/*diverse: */
+	IssmDouble  r,s;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  drag_p,drag_q;
+	IssmDouble  Neff;
+	IssmDouble  drag_coefficient;
+	IssmDouble  bed,thickness;
+	IssmDouble  gravity,rho_ice,rho_water;
+	IssmDouble  alpha_complement;
+
+	/*Recover parameters: */
+	inputs->GetInputValue(&drag_p,FrictionPEnum);
+	inputs->GetInputValue(&drag_q,FrictionQEnum);
+	this->GetInputValue(&thickness, gauss,ThicknessEnum);
+	this->GetInputValue(&bed, gauss,BedEnum);
+	this->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+
+	/*Get material parameters: */
+	gravity=matpar->GetG();
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+
+	/*If effective pressure becomes negative, sliding becomes unstable (Paterson 4th edition p 148). This is because 
+	  the water pressure is so high, the ice sheet elevates over its ice bumps and slides. But the limit behaviour 
+	  for friction should be an ice shelf sliding (no basal drag). Therefore, for any effective pressure Neff < 0, we should 
+	  replace it by Neff=0 (ie, equival it to an ice shelf)*/
+	if (Neff<0)Neff=0;
+
+	//We need the velocity magnitude to evaluate the basal stress:
+	if(strcmp(element_type,"2d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2));
+	}
+	else if (strcmp(element_type,"3d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		this->GetInputValue(&vz, gauss,vzenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
+	}
+	else _error_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+
+	alpha_complement=pow(Neff,r)*pow(vmag,(s-1));            _assert_(!xIsNan<IssmDouble>(alpha_complement));
+
+	/*Assign output pointers:*/
+	*palpha_complement=alpha_complement;
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlphaComplement(IssmDouble* palpha_complement, GaussPenta* gauss,int vxenum,int vyenum,int vzenum) {{{*/
+void Friction::GetAlphaComplement(IssmDouble* palpha_complement, GaussPenta* gauss,int vxenum,int vyenum,int vzenum){
+
+	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
+	 * FrictionGetAlphaComplement is used in control methods on drag, and it computes: 
+	 * alpha_complement= Neff ^r * vel ^s*/
+
+	/*diverse: */
+	IssmDouble  r,s;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  drag_p,drag_q;
+	IssmDouble  Neff;
+	IssmDouble  drag_coefficient;
+	IssmDouble  bed,thickness;
+	IssmDouble  gravity,rho_ice,rho_water;
+	IssmDouble  alpha_complement;
+
+	/*Recover parameters: */
+	inputs->GetInputValue(&drag_p,FrictionPEnum);
+	inputs->GetInputValue(&drag_q,FrictionQEnum);
+	this->GetInputValue(&thickness, gauss,ThicknessEnum);
+	this->GetInputValue(&bed, gauss,BedEnum);
+	this->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+
+	/*Get material parameters: */
+	gravity=matpar->GetG();
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+
+	/*If effective pressure becomes negative, sliding becomes unstable (Paterson 4th edition p 148). This is because 
+	  the water pressure is so high, the ice sheet elevates over its ice bumps and slides. But the limit behaviour 
+	  for friction should be an ice shelf sliding (no basal drag). Therefore, for any effective pressure Neff < 0, we should 
+	  replace it by Neff=0 (ie, equival it to an ice shelf)*/
+	if (Neff<0)Neff=0;
+
+	//We need the velocity magnitude to evaluate the basal stress:
+	if(strcmp(element_type,"2d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2));
+	}
+	else if (strcmp(element_type,"3d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		this->GetInputValue(&vz, gauss,vzenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
+	}
+	else _error_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+
+	alpha_complement=pow(Neff,r)*pow(vmag,(s-1));            _assert_(!xIsNan<IssmDouble>(alpha_complement));
+
+	/*Assign output pointers:*/
+	*palpha_complement=alpha_complement;
+}
+/*}}}*/
+/*FUNCTION Friction::GetInputValue{{{*/
+void Friction::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,int enum_type){
+
+	Input* input=inputs->GetInput(enum_type);
+	if(!input) _error_("input " << EnumToStringx(enum_type) << " not found");
+	input->GetInputValue(pvalue,gauss);
+
+}
+/*}}}*/
+/*FUNCTION Friction::GetInputValue{{{*/
+void Friction::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int enum_type){
+
+	Input* input=inputs->GetInput(enum_type);
+	if(!input) _error_("input " << EnumToStringx(enum_type) << " not found");
+	input->GetInputValue(pvalue,gauss);
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Friction.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Friction.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Friction.h	(revision 15396)
@@ -0,0 +1,40 @@
+/*!\file Friction.h
+ * \brief: header file for friction object
+ */
+
+#ifndef _FRICTION_H_
+#define _FRICTION_H_
+
+/*Headers:*/
+/*{{{*/
+class Inputs;
+class Matpar;
+class GaussPenta;
+class GaussTria;
+/*}}}*/
+
+class Friction{
+
+	public:
+		int analysis_type;
+
+		char* element_type;
+		Inputs* inputs;
+		Matpar* matpar;
+
+		/*methods: */
+		Friction();
+		Friction(const char* element_type, Inputs* inputs,Matpar* matpar, int analysis_type);
+		~Friction();
+
+		void  Echo(void);
+		void  GetAlpha2(IssmDouble* palpha2, GaussTria* gauss,int vxenum,int vyenum,int vzenum);
+		void  GetAlpha2(IssmDouble* palpha2, GaussPenta* gauss,int vxenum,int vyenum,int vzenum);
+		void  GetAlphaComplement(IssmDouble* alpha_complement, GaussTria* gauss,int vxenum,int vyenum,int vzenum);
+		void  GetAlphaComplement(IssmDouble* alpha_complement, GaussPenta* gauss,int vxenum,int vyenum,int vzenum);
+		void  GetInputValue(IssmDouble* pvalue,GaussTria* gauss,int enum_type);
+		void  GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int enum_type);
+
+};
+
+#endif  /* _FRICTION_H_ */
Index: /issm/trunk/src/c/classes/Loads/Icefront.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Icefront.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Icefront.cpp	(revision 15396)
@@ -0,0 +1,856 @@
+/*!\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: /issm/trunk/src/c/classes/Loads/Icefront.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Icefront.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Icefront.h	(revision 15396)
@@ -0,0 +1,104 @@
+/*!\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 15396)
+++ /issm/trunk/src/c/classes/Loads/Load.h	(revision 15396)
@@ -0,0 +1,46 @@
+/*!\file:  Load.h
+ * \brief abstract class for Load object
+ * This class is a place holder for the Icefront  and the Penpair loads.
+ * It is derived from Load, so DataSets can contain them.
+ */ 
+
+#ifndef _LOAD_H_
+#define _LOAD_H_
+
+/*Headers:*/
+/*{{{*/
+class Node;
+template <class doublematrix> class Matrix;
+template <class doubletype> class Vector;
+class Elements;
+class Loads;
+class Nodes;
+class Vertices;
+class Materials;
+class Parameters;
+
+#include "../../datastructures/datastructures.h"
+#include "../Update.h"
+
+/*}}}*/
+
+class Load: public Object,public Update{
+
+	public: 
+
+		virtual       ~Load(){};
+		virtual void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual bool  IsPenalty(void)=0;
+		virtual int   GetNumberOfNodes(void)=0;
+		virtual void  GetNodesSidList(int* sidlist)=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;
+		virtual void  CreatePVector(Vector<IssmDouble>* pf)=0;
+		virtual void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff)=0;
+		virtual void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax)=0;
+		virtual void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs, IssmDouble kmax)=0;
+		virtual void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax)=0;
+		virtual bool  InAnalysis(int analysis_type)=0;
+		virtual void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,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 15396)
+++ /issm/trunk/src/c/classes/Loads/Loads.cpp	(revision 15396)
@@ -0,0 +1,189 @@
+/*
+ * \file Loads.cpp
+ * \brief: Implementation of Loads class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <vector>
+#include <functional>
+#include <algorithm>
+
+#include "./Loads.h"
+#include "./Load.h"
+#include "../../shared/shared.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Loads::Loads(){{{*/
+Loads::Loads(){
+	enum_type=LoadsEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Loads::~Loads(){{{*/
+Loads::~Loads(){
+	return;
+}
+/*}}}*/
+
+/*Numerics:*/
+/*FUNCTION Loads::Configure{{{*/
+void Loads::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+
+	vector<Object*>::iterator object;
+	Load* load=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		load=dynamic_cast<Load*>(*object);
+		load->Configure(elements,loads,nodes,vertices,materials,parameters);
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION Loads::IsPenalty{{{*/
+bool Loads::IsPenalty(int analysis_type){
+
+	int ispenalty=0;
+	int allispenalty=0;
+
+	/*Now go through all loads, and get how many nodes they own, unless they are clone nodes: */
+	for(int i=0;i<this->Size();i++){
+
+		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+		if (load->InAnalysis(analysis_type)){
+			if(load->IsPenalty()) ispenalty++;
+		}
+	}
+
+	/*Grab sum of all cpus: */
+#ifdef _HAVE_MPI_
+	MPI_Allreduce((void*)&ispenalty,(void*)&allispenalty,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
+	ispenalty=allispenalty;
+#endif
+
+	if(ispenalty)
+	 return true;
+	else
+	 return false;
+}
+/*}}}*/
+/*FUNCTION Loads::MaxNumNodes{{{*/
+int Loads::MaxNumNodes(int analysis_type){
+
+	int max=0;
+	int allmax;
+	int numnodes=0;
+
+	/*Now go through all loads, and get how many nodes they own, unless they are clone nodes: */
+	for(int i=0;i<this->Size();i++){
+
+		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+		if (load->InAnalysis(analysis_type)){
+			numnodes=load->GetNumberOfNodes();
+			if(numnodes>max)max=numnodes;
+		}
+	}
+
+	/*Grab max of all cpus: */
+#ifdef _HAVE_MPI_
+	MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
+	max=allmax;
+#endif
+
+	return max;
+}
+/*}}}*/
+/*FUNCTION Loads::NumberOfLoads(){{{*/
+int Loads::NumberOfLoads(void){
+
+	int localloads;
+	int numberofloads;
+
+	/*Get number of local loads*/
+	localloads=this->Size();
+
+	/*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
+
+	return numberofloads;
+}
+/*}}}*/
+/*FUNCTION Loads::NumberOfLoads(int analysis){{{*/
+int Loads::NumberOfLoads(int analysis_type){
+
+	int localloads = 0;
+	int numberofloads;
+
+	/*Get number of local loads*/
+	for(int i=0;i<this->Size();i++){
+
+		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+
+		/*Check that this load corresponds to our analysis currently being carried out: */
+		if (load->InAnalysis(analysis_type)) localloads++;
+	}
+
+	/*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
+
+	return numberofloads;
+}
+/*}}}*/
+/*FUNCTION Loads::Size(){{{*/
+int Loads::Size(void){
+
+	return this->DataSet::Size();
+}
+/*}}}*/
+/*FUNCTION Loads::Size(int analysis){{{*/
+int Loads::Size(int analysis_type){
+
+	int localloads = 0;
+
+	/*Get number of local loads*/
+	for(int i=0;i<this->Size();i++){
+
+		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+
+		/*Check that this load corresponds to our analysis currently being carried out: */
+		if (load->InAnalysis(analysis_type)) localloads++;
+	}
+
+	return localloads;
+}
+/*}}}*/
+/*FUNCTION Loads::SetCurrentConfiguration{{{*/
+void Loads::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+
+	vector<Object*>::iterator object;
+	Load* load=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		load=dynamic_cast<Load*>(*object);
+		load->SetCurrentConfiguration(elements,loads,nodes,vertices,materials,parameters);
+
+	}
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Loads.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Loads.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Loads.h	(revision 15396)
@@ -0,0 +1,36 @@
+#ifndef _CONTAINER_LOADS_H_
+#define  _CONTAINER_LOADS_H_
+
+/*forward declarations */
+#include "../../datastructures/datastructures.h"
+class Materials;
+class Parameters;
+class Elements;
+class Vertices;
+class Nodes;
+
+/*!\brief Declaration of Loads class.
+ *
+ * Declaration of Loads class.  Loads are vector lists (Containers) of Load objects.
+ */ 
+class Loads: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Loads();
+		~Loads();
+
+		/*numerics*/
+		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		bool  IsPenalty(int analysis);
+		int   MaxNumNodes(int analysis);
+		int   NumberOfLoads(void);
+		int   NumberOfLoads(int analysis);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		int   Size(int analysis);
+		int   Size(void);
+
+};
+
+#endif //ifndef _LOADS_H_
Index: /issm/trunk/src/c/classes/Loads/Numericalflux.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Numericalflux.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Numericalflux.cpp	(revision 15396)
@@ -0,0 +1,976 @@
+/*!\file Numericalflux.c
+ * \brief: implementation of the Numericalflux object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "shared/shared.h"
+#include "../classes.h"
+/*}}}*/	
+
+/*Load macros*/
+#define NUMVERTICES 2
+#define NUMNODES_INTERNAL 4
+#define NUMNODES_BOUNDARY 2
+
+/*Numericalflux constructors and destructor*/
+/*FUNCTION Numericalflux::Numericalflux(){{{*/
+Numericalflux::Numericalflux(){
+	this->inputs     = NULL;
+	this->parameters = NULL;
+	this->helement   = NULL;
+	this->element    = NULL;
+	this->hnodes     = NULL;
+	this->hvertices  = NULL;
+	this->nodes      = NULL;
+}
+/*}}}*/
+/*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){
+
+	/* Intermediary */
+	int  e1,e2;
+	int  i1,i2;
+	int  j;
+	int  pos1,pos2,pos3,pos4;
+	int  num_nodes;
+	int  num_elems;
+
+	/*numericalflux constructor data: */
+	int   numericalflux_elem_ids[2];
+	int   numericalflux_mparid;
+	int   numericalflux_vertex_ids[2];
+	int   numericalflux_node_ids[4];
+	int   numericalflux_type;
+
+	int    numberofelements;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+
+	/* Get MatPar id */
+	numericalflux_mparid=numberofelements+1; //matlab indexing
+
+	/*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]
+		/* Boundary edge, only one element */
+		e1=reCast<int>(iomodel->Data(MeshEdgesEnum)[4*i+2]);
+		e2=reCast<int>(UNDEF);
+		num_elems=1;
+		num_nodes=2;
+		numericalflux_type=BoundaryEnum;
+		numericalflux_elem_ids[0]=e1;
+	}
+	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;
+		numericalflux_type=InternalEnum;
+		numericalflux_elem_ids[0]=e1;
+		numericalflux_elem_ids[1]=e2;
+	}
+
+	/*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;
+
+	/*2: Get node ids*/
+	if (numericalflux_type==InternalEnum){
+
+		/*Now, we must get the nodes of the 4 nodes located on the edge*/
+
+		/*2: Get the column where these ids are located in the index*/
+		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;
+		}
+		_assert_(pos1!=UNDEF && pos2!=UNDEF && pos3!=UNDEF && pos4!=UNDEF);
+
+		/*3: We have the id of the elements and the position of the vertices in the index
+		 * we can compute their dofs!*/
+		numericalflux_node_ids[0]=iomodel->nodecounter+3*(e1-1)+pos1;
+		numericalflux_node_ids[1]=iomodel->nodecounter+3*(e1-1)+pos2;
+		numericalflux_node_ids[2]=iomodel->nodecounter+3*(e2-1)+pos3;
+		numericalflux_node_ids[3]=iomodel->nodecounter+3*(e2-1)+pos4;
+	}
+	else{
+
+		/*2: Get the column where these ids are located in the index*/
+		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;
+		}
+		_assert_(pos1!=UNDEF && pos2!=UNDEF);
+
+		/*3: We have the id of the elements and the position of the vertices in the index
+		 * we can compute their dofs!*/
+		numericalflux_node_ids[0]=iomodel->nodecounter+3*(e1-1)+pos1;
+		numericalflux_node_ids[1]=iomodel->nodecounter+3*(e1-1)+pos2;
+	}
+
+	/*Ok, we have everything to build the object: */
+	this->id=numericalflux_id;
+	this->analysis_type=in_analysis_type;
+
+	/*Hooks: */
+	this->hnodes    =new Hook(numericalflux_node_ids,num_nodes);
+	this->hvertices =new Hook(&numericalflux_vertex_ids[0],2);
+	this->helement  =new Hook(numericalflux_elem_ids,1); // take only the first element for now
+
+	//intialize  and add as many inputs per element as requested: 
+	this->inputs=new Inputs();
+	this->inputs->AddInput(new IntInput(NumericalfluxTypeEnum,numericalflux_type));
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+	this->element=NULL;
+	this->nodes=NULL;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::~Numericalflux(){{{*/
+Numericalflux::~Numericalflux(){
+	delete inputs;
+	this->parameters=NULL;
+	delete helement;
+	delete hnodes;
+	delete hvertices;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Numericalflux::Echo {{{*/
+void Numericalflux::Echo(void){
+	_printf_("Numericalflux:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnodes->Echo();
+	hvertices->Echo();
+	helement->Echo();
+	_printf_("   parameters: " << parameters << "\n");
+	_printf_("   inputs: " << inputs << "\n");
+}
+/*}}}*/
+/*FUNCTION Numericalflux::DeepEcho {{{*/
+void Numericalflux::DeepEcho(void){
+
+	_printf_("Numericalflux:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnodes->DeepEcho();
+	hvertices->DeepEcho();
+	helement->DeepEcho();
+	_printf_("   parameters\n");
+	if(parameters)
+	 parameters->DeepEcho();
+	else
+	 _printf_("      NULL\n");
+	_printf_("   inputs\n");
+	inputs->DeepEcho();
+
+}		
+/*}}}*/
+/*FUNCTION Numericalflux::Id {{{*/
+int    Numericalflux::Id(void){
+	return id;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::ObjectEnum{{{*/
+int Numericalflux::ObjectEnum(void){
+
+	return NumericalfluxEnum;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::copy {{{*/
+Object* Numericalflux::copy() {
+
+	Numericalflux* numericalflux=NULL;
+
+	numericalflux=new Numericalflux();
+
+	/*copy fields: */
+	numericalflux->id=this->id;
+	numericalflux->analysis_type=this->analysis_type;
+	if(this->inputs){
+		numericalflux->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		numericalflux->inputs=new Inputs();
+	}
+	/*point parameters: */
+	numericalflux->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	numericalflux->hnodes    = (Hook*)this->hnodes->copy();
+	numericalflux->hvertices = (Hook*)this->hvertices->copy();
+	numericalflux->helement  = (Hook*)this->helement->copy();
+
+	/*corresponding fields*/
+	numericalflux->nodes    = (Node**)numericalflux->hnodes->deliverp();
+	numericalflux->vertices = (Vertex**)numericalflux->hvertices->deliverp();
+	numericalflux->element  = (Element*)numericalflux->helement->delivers();
+
+	return numericalflux;
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+/*FUNCTION Numericalflux::Configure {{{*/
+void  Numericalflux::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);
+
+	/*Initialize hooked fields*/
+	this->nodes    = (Node**)hnodes->deliverp();
+	this->vertices = (Vertex**)hvertices->deliverp();
+	this->element  = (Element*)helement->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::SetCurrentConfiguration {{{*/
+void  Numericalflux::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrix {{{*/
+void  Numericalflux::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+
+	/*recover some parameters*/
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*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();
+			break;
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		case AdjointBalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixAdjointBalancethickness();
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVector {{{*/
+void  Numericalflux::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*recover some parameters*/
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case PrognosticAnalysisEnum:
+			pe=CreatePVectorPrognostic();
+			break;
+		case BalancethicknessAnalysisEnum:
+			pe=CreatePVectorBalancethickness();
+			break;
+		case AdjointBalancethicknessAnalysisEnum:
+			pe=CreatePVectorAdjointBalancethickness();
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::GetNodesSidList{{{*/
+void Numericalflux::GetNodesSidList(int* sidlist){
+
+	int type;
+	inputs->GetInputValue(&type,NumericalfluxTypeEnum);
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	switch(type){
+		case InternalEnum:
+			for(int i=0;i<NUMNODES_INTERNAL;i++) sidlist[i]=nodes[i]->Sid();
+			return;
+		case BoundaryEnum:
+			for(int i=0;i<NUMNODES_BOUNDARY;i++) sidlist[i]=nodes[i]->Sid();
+			return;
+		default:
+			_error_("Numericalflux type " << EnumToStringx(type) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::GetNumberOfNodes{{{*/
+int Numericalflux::GetNumberOfNodes(void){
+
+	int type;
+	inputs->GetInputValue(&type,NumericalfluxTypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return NUMNODES_INTERNAL;
+		case BoundaryEnum:
+			return NUMNODES_BOUNDARY;
+		default:
+			_error_("Numericalflux type " << EnumToStringx(type) << " not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::IsPenalty{{{*/
+bool Numericalflux::IsPenalty(void){
+	return false;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::PenaltyCreateKMatrix {{{*/
+void  Numericalflux::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+
+	/*No stiffness loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::PenaltyCreatePVector{{{*/
+void  Numericalflux::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+
+	/*No penalty loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::InAnalysis{{{*/
+bool Numericalflux::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::SetwiseNodeConnectivity{{{*/
+void Numericalflux::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;
+}
+/*}}}*/
+
+/*Numericalflux management*/
+/*FUNCTION Numericalflux::CreateKMatrixPrognostic{{{*/
+ElementMatrix* Numericalflux::CreateKMatrixPrognostic(void){
+
+	int type;
+	inputs->GetInputValue(&type,NumericalfluxTypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreateKMatrixPrognosticInternal();
+		case BoundaryEnum:
+			return CreateKMatrixPrognosticBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixPrognosticInternal {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixPrognosticInternal(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_INTERNAL;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL1,DL2,Jdet,dt,vx,vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     B[numdof];
+	IssmDouble     Bprime[numdof];
+	IssmDouble     Ke_g1[numdof][numdof];
+	IssmDouble     Ke_g2[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMNODES_INTERNAL,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentBFlux(&B[0],gauss,index1,index2);
+		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL1=gauss->weight*Jdet*dt*UdotN/2;
+		DL2=gauss->weight*Jdet*dt*fabs(UdotN)/2;
+
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL1,1,1,0,
+					&Bprime[0],1,numdof,0,
+					&Ke_g1[0][0],0);
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL2,1,1,0,
+					&B[0],1,numdof,0,
+					&Ke_g2[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g1[i][j];
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g2[i][j];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixPrognosticBoundary {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixPrognosticBoundary(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     L[numdof];
+	IssmDouble     Ke_g[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke = NULL;
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum); _assert_(vxaverage_input);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN<=0){
+		return NULL; /*(u,n)<0 -> inflow, PenaltyCreatePVector will take care of it*/
+	}
+	else{
+		Ke=new ElementMatrix(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL=gauss->weight*Jdet*dt*UdotN;
+
+		TripleMultiply(&L[0],1,numdof,1,
+					&DL,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke_g[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g[i][j];
+	} 
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixBalancethickness{{{*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethickness(void){
+
+	int type;
+	inputs->GetInputValue(&type,NumericalfluxTypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreateKMatrixBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreateKMatrixBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixBalancethicknessInternal {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessInternal(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_INTERNAL;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL1,DL2,Jdet,vx,vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     B[numdof];
+	IssmDouble     Bprime[numdof];
+	IssmDouble     Ke_g1[numdof][numdof];
+	IssmDouble     Ke_g2[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMNODES_INTERNAL,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentBFlux(&B[0],gauss,index1,index2);
+		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL1=gauss->weight*Jdet*UdotN/2;
+		DL2=gauss->weight*Jdet*fabs(UdotN)/2;
+
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL1,1,1,0,
+					&Bprime[0],1,numdof,0,
+					&Ke_g1[0][0],0);
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL2,1,1,0,
+					&B[0],1,numdof,0,
+					&Ke_g2[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g1[i][j];
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g2[i][j];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixBalancethicknessBoundary {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessBoundary(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     L[numdof];
+	IssmDouble     Ke_g[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke = NULL;
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN<=0){
+		return NULL; /*(u,n)<0 -> inflow, PenaltyCreatePVector will take care of it*/
+	}
+	else{
+		Ke=new ElementMatrix(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL=gauss->weight*Jdet*UdotN;
+
+		TripleMultiply(&L[0],1,numdof,1,
+					&DL,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke_g[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g[i][j];
+	} 
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethickness{{{*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethickness(void){
+
+	int type;
+	inputs->GetInputValue(&type,NumericalfluxTypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreateKMatrixAdjointBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreateKMatrixAdjointBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethicknessInternal {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessInternal(void){
+
+	ElementMatrix* Ke=CreateKMatrixBalancethicknessInternal();
+	if (Ke) Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary(void){
+
+	ElementMatrix* Ke=CreateKMatrixBalancethicknessBoundary();
+	if(Ke) Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorPrognostic{{{*/
+ElementVector* Numericalflux::CreatePVectorPrognostic(void){
+
+	int type;
+	inputs->GetInputValue(&type,NumericalfluxTypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreatePVectorPrognosticInternal();
+		case BoundaryEnum:
+			return CreatePVectorPrognosticBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorPrognosticInternal{{{*/
+ElementVector* Numericalflux::CreatePVectorPrognosticInternal(void){
+
+	/*Nothing added to PVector*/
+	return NULL;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorPrognosticBoundary{{{*/
+ElementVector* Numericalflux::CreatePVectorPrognosticBoundary(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,ig,index1,index2;
+	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN,thickness;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     L[numdof];
+	GaussTria *gauss;
+
+	/*Initialize Load Vector and return if necessary*/
+	ElementVector* pe = NULL;
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input   =tria->inputs->GetInput(VxEnum);                     _assert_(vxaverage_input); 
+	Input* vyaverage_input   =tria->inputs->GetInput(VyEnum);                     _assert_(vyaverage_input);
+	Input* spcthickness_input=tria->inputs->GetInput(PrognosticSpcthicknessEnum); _assert_(spcthickness_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN>0){
+		return NULL; /*(u,n)>0 -> outflow, PenaltyCreateKMatrix will take care of it*/
+	}
+	else{
+		pe=new ElementVector(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		spcthickness_input->GetInputValue(&thickness,gauss);
+		if(xIsNan<IssmDouble>(thickness)) _error_("Cannot weakly apply constraint because NaN was provided");
+
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL= - gauss->weight*Jdet*dt*UdotN*thickness;
+
+		for(i=0;i<numdof;i++) pe->values[i] += DL*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorBalancethickness{{{*/
+ElementVector* Numericalflux::CreatePVectorBalancethickness(void){
+
+	int type;
+	inputs->GetInputValue(&type,NumericalfluxTypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreatePVectorBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreatePVectorBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorBalancethicknessInternal{{{*/
+ElementVector* Numericalflux::CreatePVectorBalancethicknessInternal(void){
+
+	/*Nothing added to PVector*/
+	return NULL;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorBalancethicknessBoundary{{{*/
+ElementVector* Numericalflux::CreatePVectorBalancethicknessBoundary(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,ig,index1,index2;
+	IssmDouble DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN,thickness;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble normal[2];
+	IssmDouble L[numdof];
+	GaussTria *gauss;
+
+	/*Initialize Load Vector and return if necessary*/
+	ElementVector* pe = NULL;
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum); _assert_(vxaverage_input); 
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	Input* thickness_input=tria->inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN>0){
+		return NULL; /*(u,n)>0 -> outflow, PenaltyCreateKMatrix will take care of it*/
+	}
+	else{
+		pe=new ElementVector(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL= - gauss->weight*Jdet*UdotN*thickness;
+
+		for(i=0;i<numdof;i++) pe->values[i] += DL*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorAdjointBalancethickness{{{*/
+ElementVector* Numericalflux::CreatePVectorAdjointBalancethickness(void){
+
+	/*No PVector for the Adjoint*/
+	return NULL;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::GetNormal {{{*/
+void Numericalflux:: GetNormal(IssmDouble* normal,IssmDouble xyz_list[4][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(pow(vector[0],2.0)+pow(vector[1],2.0));
+
+	normal[0]= + vector[1]/norm;
+	normal[1]= - vector[0]/norm;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Numericalflux.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Numericalflux.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Numericalflux.h	(revision 15396)
@@ -0,0 +1,100 @@
+/*!\file Numericalflux.h
+ * \brief: header file for icefront object
+ */
+
+#ifndef _NUMERICALFLUX_H_
+#define _NUMERICALFLUX_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Load.h"
+class Hook;
+class Parameters;
+class Inputs;
+class IoModel;
+class ElementMatrix;
+class ElementVector;
+/*}}}*/
+
+class Numericalflux: public Load {
+
+	public: 
+		int id;
+		int analysis_type;
+
+		/*Hooks*/
+		Hook *helement;
+		Hook *hnodes;
+		Hook *hvertices;
+
+		/*Corresponding fields*/
+		Element     *element;
+		Vertex     **vertices;
+		Node       **nodes;
+		Parameters  *parameters;
+		Inputs      *inputs;
+
+		/*Numericalflux constructors,destructors {{{*/
+		Numericalflux();
+		Numericalflux(int numericalflux_id,int i, IoModel* iomodel,int analysis_type);
+		~Numericalflux();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void InputUpdateFromVector(IssmDouble* vector, int name, int type){/*Do nothing*/}
+		void 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*/};
+		void InputUpdateFromConstant(bool constant, int name){_error_("Not implemented yet!");}
+		void InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		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 GetNodesSidList(int* sidlist);
+		int  GetNumberOfNodes(void);
+		void CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		bool IsPenalty(void);
+		void PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
+		void PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
+		void PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		void SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,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* CreateKMatrixBalancethickness(void);
+		ElementMatrix* CreateKMatrixBalancethicknessInternal(void);
+		ElementMatrix* CreateKMatrixBalancethicknessBoundary(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethickness(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethicknessInternal(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethicknessBoundary(void);
+		ElementVector* CreatePVectorPrognostic(void);
+		ElementVector* CreatePVectorPrognosticInternal(void);
+		ElementVector* CreatePVectorPrognosticBoundary(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		ElementVector* CreatePVectorBalancethicknessInternal(void);
+		ElementVector* CreatePVectorBalancethicknessBoundary(void);
+		ElementVector* CreatePVectorAdjointBalancethickness(void);
+		/*}}}*/
+
+};
+
+#endif  /* _NUMERICALFLUX_H_ */
Index: /issm/trunk/src/c/classes/Loads/Pengrid.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Pengrid.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Pengrid.cpp	(revision 15396)
@@ -0,0 +1,774 @@
+/*!\file Pengrid.c
+ * \brief: implementation of the Pengrid 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"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES   1
+
+/*Pengrid constructors and destructor*/
+/*FUNCTION Pengrid::Pengrid(){{{*/
+Pengrid::Pengrid(){
+	this->inputs=NULL;
+	this->parameters=NULL;
+	this->hnode=NULL;
+	this->node=NULL;
+	this->helement=NULL;
+	this->element=NULL;
+	this->hmatpar=NULL;
+	this->matpar=NULL;
+
+	/*not active, not zigzagging: */
+	active=0;
+	zigzag_counter=0;
+
+}
+/*}}}*/
+/*FUNCTION Pengrid::Pengrid(int index, int id, IoModel* iomodel,int analysis_type){{{*/
+Pengrid::Pengrid(int id, int index, IoModel* iomodel, int in_analysis_type){ //i is the element index
+
+	int pengrid_node_id;
+	int pengrid_matpar_id;
+	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_(id);
+
+	/*id: */
+	this->id=id;
+	this->analysis_type=in_analysis_type;
+
+	/*hooks: */
+	pengrid_node_id=iomodel->nodecounter+index+1;
+	pengrid_element_id=iomodel->singlenodetoelementconnectivity[index];
+	_assert_(pengrid_element_id);
+	pengrid_matpar_id=numberofelements+1; //refers to the constant material parameters object
+
+	this->hnode=new Hook(&pengrid_node_id,1);
+	this->helement=new Hook(&pengrid_element_id,1);
+	this->hmatpar=new Hook(&pengrid_matpar_id,1);
+
+	//initialize inputs: none needed
+	this->inputs=new Inputs();
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+	this->node=NULL;
+	this->element=NULL;
+	this->matpar=NULL;
+
+	//let's not forget internals
+	this->active=0;
+	this->zigzag_counter=0;
+
+}
+/*}}}*/
+/*FUNCTION Pengrid::~Pengrid(){{{*/
+Pengrid::~Pengrid(){
+	delete inputs;
+	delete hnode;
+	delete helement;
+	delete hmatpar;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Pengrid::Echo {{{*/
+void Pengrid::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Pengrid::DeepEcho{{{*/
+void Pengrid::DeepEcho(void){
+
+	_printf_("Pengrid:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnode->DeepEcho();
+	helement->DeepEcho();
+	hmatpar->DeepEcho();
+	_printf_("   active " << this->active << "\n");
+	_printf_("   zigzag_counter " << this->zigzag_counter << "\n");
+	_printf_("   parameters\n");
+	parameters->DeepEcho();
+	_printf_("   inputs\n");
+	inputs->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Pengrid::Id {{{*/
+int    Pengrid::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Pengrid::ObjectEnum{{{*/
+int Pengrid::ObjectEnum(void){
+
+	return PengridEnum;
+}
+/*}}}*/
+/*FUNCTION Icefront::copy {{{*/
+Object* Pengrid::copy() {
+
+	Pengrid* pengrid=NULL;
+
+	pengrid=new Pengrid();
+
+	/*copy fields: */
+	pengrid->id=this->id;
+	pengrid->analysis_type=this->analysis_type;
+	if(this->inputs){
+		pengrid->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		pengrid->inputs=new Inputs();
+	}
+	/*point parameters: */
+	pengrid->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	pengrid->hnode=(Hook*)this->hnode->copy();
+	pengrid->hmatpar=(Hook*)this->hmatpar->copy();
+	pengrid->helement=(Hook*)this->helement->copy();
+
+	/*corresponding fields*/
+	pengrid->node  =(Node*)pengrid->hnode->delivers();
+	pengrid->matpar =(Matpar*)pengrid->hmatpar->delivers();
+	pengrid->element=(Element*)pengrid->helement->delivers();
+
+	//let's not forget internals
+	pengrid->active=this->active=0;
+	pengrid->zigzag_counter=this->zigzag_counter=0;
+
+	return pengrid;
+
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+/*FUNCTION Pengrid::Configure {{{*/
+void  Pengrid::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+	/*Take care of hooking up all objects for this load, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	hnode->configure(nodesin);
+	helement->configure(elementsin);
+	hmatpar->configure(materialsin);
+
+	/*Get corresponding fields*/
+	node=(Node*)hnode->delivers();
+	element=(Element*)helement->delivers();
+	matpar=(Matpar*)hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+}
+/*}}}*/
+/*FUNCTION Pengrid::SetCurrentConfiguration {{{*/
+void  Pengrid::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Pengrid::CreateKMatrix {{{*/
+void  Pengrid::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Pengrid::CreatePVector {{{*/
+void  Pengrid::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Pengrid::GetNodesSidList{{{*/
+void Pengrid::GetNodesSidList(int* sidlist){
+
+	_assert_(sidlist);
+	_assert_(node);
+
+	sidlist[0]=node->Sid();
+}
+/*}}}*/
+/*FUNCTION Pengrid::GetNumberOfNodes{{{*/
+int Pengrid::GetNumberOfNodes(void){
+
+	return NUMVERTICES;
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreateMatrix {{{*/
+void  Pengrid::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticStokes(kmax);
+			break;
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum:
+			Ke=PenaltyCreateKMatrixThermal(kmax);
+			break;
+		case MeltingAnalysisEnum:
+			Ke=PenaltyCreateKMatrixMelting(kmax);
+			break;
+		#endif
+		#ifdef _HAVE_HYDROLOGY_
+		case HydrologyDCInefficientAnalysisEnum:
+			Ke=PenaltyCreateKMatrixHydrologyDCInefficient(kmax);
+			break;
+		#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreatePVector {{{*/
+void  Pengrid::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum:
+			pe=PenaltyCreatePVectorThermal(kmax);
+			break;
+		case MeltingAnalysisEnum:
+			pe=PenaltyCreatePVectorMelting(kmax);
+			break;
+		case DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
+			break;
+		#endif
+		#ifdef _HAVE_HYDROLOGY_
+		case HydrologyDCInefficientAnalysisEnum:
+			pe=PenaltyCreatePVectorHydrologyDCInefficient(kmax);
+			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 Pengrid::InAnalysis{{{*/
+bool Pengrid::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
+/*FUNCTION Pengrid::IsPenalty{{{*/
+bool Pengrid::IsPenalty(void){
+	return true;
+}
+/*}}}*/
+/*FUNCTION Pengrid::SetwiseNodeConnectivity{{{*/
+void Pengrid::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;
+
+	if(!flags[this->node->Sid()]){
+
+		/*flag current node so that no other element processes it*/
+		flags[this->node->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(node->indexing.fsize){
+					if(this->node->IsClone())
+					 o_nz += 1;
+					else
+					 d_nz += 1;
+				}
+				break;
+			case GsetEnum:
+				if(node->indexing.gsize){
+					if(this->node->IsClone())
+					 o_nz += 1;
+					else
+					 d_nz += 1;
+				}
+				break;
+			case SsetEnum:
+				if(node->indexing.ssize){
+					if(this->node->IsClone())
+					 o_nz += 1;
+					else
+					 d_nz += 1;
+				}
+				break;
+			default: _error_("not supported");
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+/*FUNCTION Pengrid::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
+void  Pengrid::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*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){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
+void  Pengrid::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*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){
+	switch(name){
+
+		case MeltingOffsetEnum:
+			inputs->AddInput(new DoubleInput(name,constant));
+			return;
+
+	}
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromConstant(int constant, int name) {{{*/
+void  Pengrid::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromConstant(bool constant, int name) {{{*/
+void  Pengrid::InputUpdateFromConstant(bool constant, int name){
+
+	switch(name){
+
+		case ResetPenaltiesEnum:
+			if (constant) zigzag_counter=0;
+			return;
+
+	}
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromSolution{{{*/
+void  Pengrid::InputUpdateFromSolution(IssmDouble* solution){
+	/*Nothing updated yet*/
+}
+/*}}}*/		
+
+/*Pengrid management:*/
+/*FUNCTION Pengrid::ConstraintActivate {{{*/
+void  Pengrid::ConstraintActivate(int* punstable){
+
+	int analysis_type;
+
+	/*Retrieve parameters: */
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	if (analysis_type==DiagnosticHorizAnalysisEnum){
+		/*No penalty to check*/
+		return;
+	}
+	#ifdef _HAVE_THERMAL_
+	else if (analysis_type==ThermalAnalysisEnum){
+		ConstraintActivateThermal(punstable);
+	}
+	else if (analysis_type==MeltingAnalysisEnum){
+		/*No penalty to check*/
+		return;
+	}
+	#endif
+	#ifdef _HAVE_HYDROLOGY_
+	else if (analysis_type==HydrologyDCInefficientAnalysisEnum){
+		ConstraintActivateHydrologyDCInefficient(punstable);
+		return;
+	}
+	#endif
+	else{
+		_error_("analysis: " << EnumToStringx(analysis_type) << " not supported yet");
+	}
+
+}
+/*}}}*/
+#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 {{{*/
+void  Pengrid::ConstraintActivateThermal(int* punstable){
+
+	//   The penalty is stable if it doesn't change during to successive iterations.   
+
+	int        found=0;
+	const int  numnodes=1;
+	IssmDouble pressure;
+	IssmDouble temperature;
+	IssmDouble t_pmp;
+	int        new_active;
+	int        unstable=0;
+	int        reset_penalties=0;
+	int        penalty_lock;
+
+	/*recover pointers: */
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()){
+		unstable=0;
+		*punstable=unstable;
+		return;
+	}
+
+	//First recover pressure and temperature values, using the element: */
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperaturePicardEnum);
+
+	//Recover our data:
+	parameters->FindParam(&penalty_lock,ThermalPenaltyLockEnum);
+
+	//Compute pressure melting point
+	t_pmp=matpar->TMeltingPoint(pressure);
+
+	//Figure out if temperature is over melting_point, in which case, this penalty needs to be activated.
+
+	if (temperature>t_pmp){
+		new_active=1;
+	}
+	else{
+		new_active=0;
+	}
+
+	//Figure out stability of this penalty
+	if (active==new_active){
+		unstable=0;
+	}
+	else{
+		unstable=1;
+		if(penalty_lock)zigzag_counter++;
+	}
+
+	/*If penalty keeps zigzagging more than 5 times: */
+	if(penalty_lock){
+		if(zigzag_counter>penalty_lock){
+			unstable=0;
+			active=1;
+		}
+	}
+
+	//Set penalty flag
+	active=new_active;
+
+	//*Assign output pointers:*/
+	*punstable=unstable;
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreateKMatrixMelting {{{*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixMelting(IssmDouble kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	IssmDouble pressure,temperature,t_pmp;
+	IssmDouble penalty_factor;
+
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,1,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperatureEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
+
+	/*Add penalty load*/
+	if (temperature<t_pmp){ //If T<Tpmp, there must be no melting. Therefore, melting should be  constrained to 0 when T<Tpmp, instead of using spcs, use penalties
+		Ke->values[0]=kmax*pow((IssmDouble)10,penalty_factor);
+	}
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreateKMatrixThermal {{{*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixThermal(IssmDouble kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	IssmDouble    penalty_factor;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	Ke->values[0]=kmax*pow((IssmDouble)10,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreatePVectorMelting {{{*/
+ElementVector* Pengrid::PenaltyCreatePVectorMelting(IssmDouble kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	IssmDouble pressure;
+	IssmDouble temperature;
+	IssmDouble melting_offset;
+	IssmDouble t_pmp;
+	IssmDouble dt,penalty_factor;
+
+	/*recover pointers: */
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()) return NULL;
+	ElementVector* pe=new ElementVector(&node,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperatureEnum);
+	inputs->GetInputValue(&melting_offset,MeltingOffsetEnum);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
+
+	/*Add penalty load
+	  This time, the penalty must have the same value as the one used for the thermal computation
+	  so that the corresponding melting can be computed correctly
+	  In the thermal computation, we used kmax=melting_offset, and the same penalty_factor*/
+	if (temperature<t_pmp){ //%no melting
+		pe->values[0]=0;
+	}
+	else{
+		if (reCast<bool>(dt)) pe->values[0]=melting_offset*pow((IssmDouble)10,penalty_factor)*(temperature-t_pmp)/dt;
+		else    pe->values[0]=melting_offset*pow((IssmDouble)10,penalty_factor)*(temperature-t_pmp);
+	}
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreatePVectorThermal {{{*/
+ElementVector* Pengrid::PenaltyCreatePVectorThermal(IssmDouble kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	IssmDouble pressure;
+	IssmDouble t_pmp;
+	IssmDouble penalty_factor;
+
+	Penta* penta=(Penta*)element;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementVector* pe=new ElementVector(&node,1,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
+
+	pe->values[0]=kmax*pow((IssmDouble)10,penalty_factor)*t_pmp;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+#endif
+#ifdef _HAVE_HYDROLOGY_
+/*FUNCTION Pengrid::ConstraintActivateHydrologyDCInefficient{{{*/
+void  Pengrid::ConstraintActivateHydrologyDCInefficient(int* punstable){
+
+	//   The penalty is stable if it doesn't change during two consecutive iterations.   
+	const int  numnodes        = 1;
+	int        unstable        = 0;
+	int        reset_penalties = 0;
+	int        found           = 0;	
+	int        penalty_lock;
+	int        new_active;
+	IssmDouble pressure;
+	IssmDouble h;
+	IssmDouble h_max;	
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if(node->IsClone()){
+		unstable=0;
+		*punstable=unstable;
+		return;
+	}
+
+	/*Get sediment water head h*/
+	element->GetInputValue(&h,node,SedimentHeadEnum);
+	element->GetHydrologyDCInefficientHmax(&h_max,node);
+	if (h>h_max)
+	 new_active=1;
+	else
+	 new_active=0;
+
+	if(this->active==new_active)
+	 unstable=0;
+	else
+	 unstable=1;
+
+	/*Set penalty flag*/
+	this->active=new_active;
+
+	/*Assign output pointers:*/
+	*punstable=unstable;
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreateKMatrixHydrologyDCInefficient {{{*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixHydrologyDCInefficient(IssmDouble kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	IssmDouble    penalty_factor;
+
+	/*Retrieve parameters*/
+	parameters->FindParam(&penalty_factor,HydrologydcPenaltyFactorEnum);
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,NUMVERTICES,this->parameters);
+
+	Ke->values[0]=kmax*pow(10.,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreatePVectorHydrologyDCInefficient {{{*/
+ElementVector* Pengrid::PenaltyCreatePVectorHydrologyDCInefficient(IssmDouble kmax){
+
+	const int  numdof=NUMVERTICES*NDOF1;
+	IssmDouble h_max;
+	IssmDouble penalty_factor;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementVector* pe=new ElementVector(&node,1,this->parameters);
+
+	/*Retrieve parameters*/
+	parameters->FindParam(&penalty_factor,HydrologydcPenaltyFactorEnum);
+
+	/*Get h_max and compute penalty*/
+	element->GetHydrologyDCInefficientHmax(&h_max,node);
+	pe->values[0]=kmax*pow(10.,penalty_factor)*h_max;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+#endif
+/*FUNCTION Pengrid::ResetConstraint {{{*/
+void  Pengrid::ResetConstraint(void){
+	active=0;
+	zigzag_counter=0;
+}
+/*}}}*/
+/*FUNCTION Pengrid::UpdateInputs {{{*/
+void  Pengrid::UpdateInputs(IssmDouble* solution){
+	_error_("not supported yet!");
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Pengrid.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Pengrid.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Pengrid.h	(revision 15396)
@@ -0,0 +1,111 @@
+/*!\file Pengrid.h
+ * \brief: header file for pengrid object */
+
+#ifndef _PENGRID_H_
+#define _PENGRID_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./Load.h"
+class Hook;
+class Inputs;
+class Parameters;
+class IoModel;
+/*}}}*/
+
+class Pengrid: public Load{
+
+	private: 
+
+		int		id;
+		int analysis_type;
+
+		/*Hooks*/
+		Hook* hnode;  //hook to 1 node
+		Hook* helement;  //hook to 1 element
+		Hook* hmatpar; //hook to 1 matpar
+
+		/*Corresponding fields*/
+		Node    *node;
+		Element *element;
+		Matpar  *matpar;
+
+		Parameters* parameters; //pointer to solution parameters
+		Inputs*  inputs;
+
+		/*internals: */
+		int active;
+		int zigzag_counter;
+
+	public:
+
+		/*Pengrid constructors, destructors {{{*/
+		Pengrid();
+		Pengrid(int index, int id, IoModel* iomodel,int analysis_type);
+		~Pengrid();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*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);
+		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){_error_("Not implemented yet");};
+		void  GetNodesSidList(int* sidlist);
+		int   GetNumberOfNodes(void);
+		bool  IsPenalty(void);
+		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
+		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,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);
+		ElementMatrix* PenaltyCreateKMatrixMelting(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorThermal(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorMelting(IssmDouble kmax);
+		void           ConstraintActivateThermal(int* punstable);
+		#endif
+		#ifdef _HAVE_HYDROLOGY_
+		ElementMatrix* PenaltyCreateKMatrixHydrologyDCInefficient(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorHydrologyDCInefficient(IssmDouble kmax);
+		void           ConstraintActivateHydrologyDCInefficient(int* punstable);
+		#endif
+		void  ConstraintActivate(int* punstable);
+		void  UpdateInputs(IssmDouble* solution);
+		void  ResetConstraint(void);
+		/*}}}*/
+
+};
+
+#endif  /* _PENGRID_H_ */
Index: /issm/trunk/src/c/classes/Loads/Penpair.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Penpair.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Penpair.cpp	(revision 15396)
@@ -0,0 +1,414 @@
+/*!\file Penpair.c
+ * \brief: implementation of the Penpair 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"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 2
+
+/*Penpair constructors and destructor*/
+/*FUNCTION Penpair::constructor {{{*/
+Penpair::Penpair(){
+
+	this->hnodes=NULL;
+	this->nodes=NULL;
+	this->parameters=NULL;
+	return;
+}
+/*}}}*/
+/*FUNCTION Penpair::creation {{{*/
+Penpair::Penpair(int penpair_id, int* penpair_node_ids,int in_analysis_type){
+
+	this->id=penpair_id;
+	this->analysis_type=in_analysis_type;
+	this->hnodes=new Hook(penpair_node_ids,2);
+	this->parameters=NULL;
+	this->nodes=NULL;
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Penpair::destructor {{{*/
+Penpair::~Penpair(){
+	delete hnodes;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Penpair::Echo {{{*/
+void Penpair::Echo(void){
+
+	_printf_("Penpair:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnodes->Echo();
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Penpair::DeepEcho {{{*/
+void Penpair::DeepEcho(void){
+
+	_printf_("Penpair:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnodes->DeepEcho();
+
+	return;
+}		
+/*}}}*/
+/*FUNCTION Penpair::Id {{{*/
+int    Penpair::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Penpair::ObjectEnum{{{*/
+int Penpair::ObjectEnum(void){
+
+	return PenpairEnum;
+}
+/*}}}*/
+/*FUNCTION Penpair::copy {{{*/
+Object* Penpair::copy() {
+
+	Penpair* penpair=NULL;
+
+	penpair=new Penpair();
+
+	/*copy fields: */
+	penpair->id=this->id;
+	penpair->analysis_type=this->analysis_type;
+
+	/*now deal with hooks and objects: */
+	penpair->hnodes=(Hook*)this->hnodes->copy();
+	penpair->nodes =(Node**)penpair->hnodes->deliverp();
+
+	/*point parameters: */
+	penpair->parameters=this->parameters;
+
+	return penpair;
+
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+/*FUNCTION Penpair::Configure {{{*/
+void  Penpair::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);
+
+	/*Initialize hooked fields*/
+	this->nodes  =(Node**)hnodes->deliverp();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+}
+/*}}}*/
+/*FUNCTION Penpair::SetCurrentConfiguration {{{*/
+void  Penpair::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Penpair::CreateKMatrix {{{*/
+void  Penpair::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+	/*If you code this piece, don't forget that a penalty will be inactive if it is dealing with clone nodes*/
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Penpair::CreatePVector {{{*/
+void  Penpair::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Penpair::CreateJacobianMatrix{{{*/
+void  Penpair::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){
+	this->CreateKMatrix(Jff,NULL);
+}
+/*}}}*/
+/*FUNCTION Penpair::GetNodesSidList{{{*/
+void Penpair::GetNodesSidList(int* sidlist){
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->Sid();
+}
+/*}}}*/
+/*FUNCTION Penpair::GetNumberOfNodes{{{*/
+int Penpair::GetNumberOfNodes(void){
+
+	return NUMVERTICES;
+}
+/*}}}*/
+/*FUNCTION Penpair::IsPenalty{{{*/
+bool Penpair::IsPenalty(void){
+	return true;
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateKMatrix {{{*/
+void  Penpair::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case DiagnosticHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+			break;
+		case PrognosticAnalysisEnum:
+			Ke=PenaltyCreateKMatrixPrognostic(kmax);
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreatePVector {{{*/
+void  Penpair::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+	/*No loads applied, do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateJacobianMatrix{{{*/
+void  Penpair::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){
+	this->PenaltyCreateKMatrix(Jff,NULL,kmax);
+}
+/*}}}*/
+/*FUNCTION Penpair::InAnalysis{{{*/
+bool Penpair::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
+/*FUNCTION Penpair::SetwiseNodeConnectivity{{{*/
+void Penpair::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<NUMVERTICES;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;
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+/*FUNCTION Penpair::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
+void  Penpair::InputUpdateFromConstant(IssmDouble constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromConstant(int constant, int name) {{{*/
+void  Penpair::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromConstant(bool constant, int name) {{{*/
+void  Penpair::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
+void  Penpair::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*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){
+
+	int    approximation0=nodes[0]->GetApproximation();
+	int    approximation1=nodes[1]->GetApproximation();
+
+	switch(approximation0){
+		case MacAyealApproximationEnum:
+			switch(approximation1){
+				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				default: _error_("not supported yet");
+			}
+		case PattynApproximationEnum:
+			switch(approximation1){
+				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				default: _error_("not supported yet");
+			}
+		case StokesApproximationEnum:
+			switch(approximation1){
+				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				default: _error_("not supported yet");
+			}
+		case NoneApproximationEnum:
+			switch(approximation1){
+				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				default: _error_("not supported yet");
+			}
+		default: _error_("not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn {{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn(IssmDouble kmax){
+
+	const int numdof=NUMVERTICES*NDOF2;
+	IssmDouble penalty_offset;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+
+	//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);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticStokes {{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticStokes(IssmDouble kmax){
+
+	const int numdof=NUMVERTICES*NDOF4;
+	IssmDouble penalty_offset;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+
+	//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);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixPrognostic {{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixPrognostic(IssmDouble kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	IssmDouble penalty_factor;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_factor,PrognosticPenaltyFactorEnum);
+
+	//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);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Penpair.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Penpair.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Penpair.h	(revision 15396)
@@ -0,0 +1,76 @@
+/*!\file Penpair.h
+ * \brief: header file for penpair object */
+
+#ifndef _PENPAIR_H_
+#define _PENPAIR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Load.h"
+#include "../Node.h"
+#include "../Elements/Element.h"
+
+class Element;
+/*}}}*/
+
+class Penpair: public Load{
+
+	private: 
+		int          id;
+		int          analysis_type;
+		Hook        *hnodes;          //hook to 2 nodes
+		Node       **nodes;
+		Parameters  *parameters;      //pointer to solution parameters
+
+	public:
+
+		/*Penpair constructors, destructors: {{{*/
+		Penpair();
+		Penpair(int penpair_id,int* penpair_node_ids,int analysis_type);
+		~Penpair();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*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);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		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);
+		void  GetNodesSidList(int* sidlist);
+		int   GetNumberOfNodes(void);
+		bool  IsPenalty(void);
+		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff,Matrix<IssmDouble>* Kfs,IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax);
+		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int 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);
+		/*}}}*/
+};
+
+#endif  /* _PENPAIR_H_ */
Index: /issm/trunk/src/c/classes/Loads/Riftfront.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Riftfront.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Riftfront.cpp	(revision 15396)
@@ -0,0 +1,961 @@
+/*!\file Riftfront.cpp
+ * \brief: implementation of the Riftfront object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "shared/shared.h"
+#include "modules/ModelProcessorx/ModelProcessorx.h"
+#include "../classes.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 2
+
+/*Riftfront constructors and destructor*/
+/*FUNCTION Riftfront::Riftfront(){{{*/
+Riftfront::Riftfront(){
+	this->inputs=NULL;
+	this->parameters=NULL;
+	this->hnodes=NULL;
+	this->helements=NULL;
+	this->hmatpar=NULL;
+	this->nodes=NULL;
+	this->elements=NULL;
+	this->matpar=NULL;
+}
+/*}}}*/
+/*FUNCTION Riftfront::Riftfront(int id, int i, IoModel* iomodel,int analysis_type){{{*/
+Riftfront::Riftfront(int riftfront_id,int i, IoModel* iomodel,int riftfront_analysis_type){
+
+	/*data: */
+	int    riftfront_node_ids[2];
+	int    riftfront_elem_ids[2];
+	int    riftfront_matpar_id;
+	int    riftfront_type;
+	int    riftfront_fill;
+	IssmDouble riftfront_friction;
+	IssmDouble riftfront_fractionincrement;
+	bool   riftfront_shelf;
+	int    numberofelements;
+	int    penalty_lock;
+
+	/*intermediary: */
+	int el1    ,el2;
+	int node1  ,node2;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&penalty_lock,DiagnosticRiftPenaltyLockEnum);
+
+	/*Ok, retrieve all the data needed to add a penalty between the two nodes: */
+	el1=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+2));
+	el2=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+3)) ;
+
+	node1=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+0));
+	node2=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+1));
+
+	/*id: */
+	this->id=riftfront_id;
+	this->analysis_type=riftfront_analysis_type;
+
+	/*hooks: */
+	riftfront_node_ids[0]=iomodel->nodecounter+node1;
+	riftfront_node_ids[1]=iomodel->nodecounter+node2;
+	riftfront_elem_ids[0]=el1;
+	riftfront_elem_ids[1]=el2;
+	riftfront_matpar_id=numberofelements+1; //matlab indexing
+
+	/*Hooks: */
+	this->hnodes=new Hook(riftfront_node_ids,2);
+	this->helements=new Hook(riftfront_elem_ids,2);
+	this->hmatpar=new Hook(&riftfront_matpar_id,1);
+
+	/*computational parameters: */
+	this->active=0;
+	this->frozen=0;
+	this->counter=0;
+	this->prestable=0;
+	this->penalty_lock=penalty_lock;
+	this->material_converged=0;
+	this->normal[0]=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+4);
+	this->normal[1]=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+5);
+	this->length=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+6);
+	this->fraction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+9);
+	this->state=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+11));
+
+	//intialize inputs, and add as many inputs per element as requested: 
+	this->inputs=new Inputs();
+
+	riftfront_type=SegmentRiftfrontEnum;
+	riftfront_fill = reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+7));
+	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]);
+
+	this->inputs->AddInput(new IntInput(RiftfrontTypeEnum,riftfront_type));
+	this->inputs->AddInput(new IntInput(FillEnum,riftfront_fill));
+	this->inputs->AddInput(new DoubleInput(FrictionEnum,riftfront_friction));
+	this->inputs->AddInput(new DoubleInput(FractionIncrementEnum,riftfront_fractionincrement));
+	this->inputs->AddInput(new BoolInput(SegmentOnIceShelfEnum,riftfront_shelf));
+
+	//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->elements= NULL;
+	this->matpar= NULL;
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::~Riftfront(){{{*/
+Riftfront::~Riftfront(){
+	delete inputs;
+	this->parameters=NULL;
+
+	delete hnodes;
+	delete helements;
+	delete hmatpar;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Riftfront::Echo {{{*/
+void Riftfront::Echo(void){
+
+	Input* input=NULL;
+	int fill;
+	IssmDouble friction,fractionincrement;
+
+	/*recover some inputs first: */
+	input=(Input*)this->inputs->GetInput(FillEnum); input->GetInputValue(&fill);
+	input=(Input*)this->inputs->GetInput(FrictionEnum); input->GetInputValue(&friction);
+	input=(Input*)this->inputs->GetInput(FractionIncrementEnum); input->GetInputValue(&fractionincrement);
+
+	_printf_("Riftfront:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   hnodes: " << hnodes << "\n");
+	_printf_("   helements: " << helements << "\n");
+	_printf_("   hmatpar: " << hmatpar << "\n");
+	_printf_("   parameters: " << parameters << "\n");
+	_printf_("   inputs: " << inputs << "\n");
+	_printf_("   internal parameters: \n");
+	_printf_("   normal: " << normal[0] << "|" << normal[1] << "\n");
+	_printf_("   length: " << length << "\n");
+	_printf_("   penalty_lock: " << penalty_lock << "\n");
+	_printf_("   active: " <<(active ? "true":"false") << "\n");
+	_printf_("   counter: " << counter << "\n");
+	_printf_("   prestable: " << (prestable ? "true":"false") << "\n");
+	_printf_("   material_converged: " << (material_converged ? "true":"false") << "\n");
+	_printf_("   fill: " << fill << "\n");
+	_printf_("   friction: " << friction << "\n");
+	_printf_("   fraction: " << fraction << "\n");
+	_printf_("   fractionincrement: " << fractionincrement << "\n");
+	_printf_("   state: " << state << "\n");
+	_printf_("   frozen: " << (frozen ? "true":"false") << "\n");
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::DeepEcho{{{*/
+void Riftfront::DeepEcho(void){
+
+	_printf_("Riftfront:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnodes->DeepEcho();
+	helements->DeepEcho();
+	hmatpar->DeepEcho();
+	_printf_("   parameters\n");
+	if(parameters)parameters->DeepEcho();
+	_printf_("   inputs\n");
+	if(inputs)inputs->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Riftfront::Id {{{*/
+int    Riftfront::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Riftfront::ObjectEnum{{{*/
+int Riftfront::ObjectEnum(void){
+
+	return RiftfrontEnum;
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::copy {{{*/
+Object* Riftfront::copy() {
+
+	Riftfront* riftfront=NULL;
+
+	riftfront=new Riftfront();
+
+	/*copy fields: */
+	riftfront->id=this->id;
+	riftfront->analysis_type=this->analysis_type;
+	if(this->inputs){
+		riftfront->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		riftfront->inputs=new Inputs();
+	}
+	/*point parameters: */
+	riftfront->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	riftfront->hnodes=(Hook*)this->hnodes->copy();
+	riftfront->helements=(Hook*)this->helements->copy();
+	riftfront->hmatpar=(Hook*)this->hmatpar->copy();
+
+	/*corresponding fields*/
+	riftfront->nodes   =(Node**)riftfront->hnodes->deliverp();
+	riftfront->elements=(Element**)riftfront->helements->deliverp();
+	riftfront->matpar  =(Matpar*)riftfront->hmatpar->delivers();
+
+	/*internal data: */
+	riftfront->penalty_lock=this->penalty_lock;
+	riftfront->active=this->active;
+	riftfront->frozen=this->frozen;
+	riftfront->state=this->state;
+	riftfront->counter=this->counter;
+	riftfront->prestable=this->prestable;
+	riftfront->material_converged=this->material_converged;
+	riftfront->normal[0]=this->normal[0];
+	riftfront->normal[1]=this->normal[1];
+	riftfront->length=this->length;
+	riftfront->fraction=this->fraction;
+
+	return riftfront;
+
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+/*FUNCTION Riftfront::InputUpdateFromConstant(bool constant,int name) {{{*/
+void  Riftfront::InputUpdateFromConstant(bool constant,int name){
+
+	/*Check that name is a Riftfront input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new BoolInput(name,constant));
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::InputUpdateFromConstant(IssmDouble constant,int name) {{{*/
+void  Riftfront::InputUpdateFromConstant(IssmDouble constant,int name){
+
+	/*Check that name is a Riftfront input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new DoubleInput(name,constant));
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::InputUpdateFromConstant(IssmDouble* constant,int name) {{{*/
+void    Riftfront::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+
+	/*Check that name is a Riftfront input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	_error_("not implemented yet");
+	//this->inputs->AddInput(new DoubleInput(name,constant));
+
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+/*FUNCTION Riftfront::Configure {{{*/
+void  Riftfront::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(nodesin);
+	helements->configure(elementsin);
+	hmatpar->configure(materialsin);
+
+	/*Initialize hooked fields*/
+	this->nodes   =(Node**)hnodes->deliverp();
+	this->elements=(Element**)helements->deliverp();
+	this->matpar  =(Matpar*)hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::IsPenalty{{{*/
+bool Riftfront::IsPenalty(void){
+	return true;
+}
+/*}}}*/
+/*FUNCTION Riftfront::SetCurrentConfiguration {{{*/
+void  Riftfront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::PenaltyCreateKMatrix {{{*/
+void  Riftfront::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case DiagnosticHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+			break;
+		case AdjointHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Riftfront::PenaltyCreatePVector {{{*/
+void  Riftfront::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case DiagnosticHorizAnalysisEnum:
+			pe=PenaltyCreatePVectorDiagnosticHoriz(kmax);
+			break;
+		case AdjointHorizAnalysisEnum:
+			/*No penalty applied on load vector*/
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Riftfront::CreateKMatrix {{{*/
+void  Riftfront::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Riftfront::CreatePVector {{{*/
+void  Riftfront::CreatePVector(Vector<IssmDouble>* pf){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Riftfront::GetNodesSidList{{{*/
+void Riftfront::GetNodesSidList(int* sidlist){
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->Sid();
+}
+/*}}}*/
+/*FUNCTION Riftfront::GetNumberOfNodes{{{*/
+int Riftfront::GetNumberOfNodes(void){
+
+	return NUMVERTICES;
+}
+/*}}}*/
+/*FUNCTION Riftfront::InAnalysis{{{*/
+bool Riftfront::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+/*FUNCTION Riftfront::SetwiseNodeConnectivity{{{*/
+void Riftfront::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<NUMVERTICES;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;
+}
+/*}}}*/
+
+/*Riftfront numerics*/
+/*FUNCTION Riftfront::PenaltyCreateKMatrixDiagnosticHoriz {{{*/
+ElementMatrix* Riftfront::PenaltyCreateKMatrixDiagnosticHoriz(IssmDouble kmax){
+
+	const int   numdof = NDOF2*NUMVERTICES;
+	int         dofs[1]             = {0};
+	IssmDouble  thickness;
+	IssmDouble  h[2];
+	IssmDouble  penalty_offset;
+	IssmDouble  friction;
+
+	/*Objects: */
+	Tria       *tria1               = NULL;
+	Tria       *tria2               = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Initialize Element Matrix*/
+	if(!this->active) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*Get some parameters: */
+	this->parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+	this->inputs->GetInputValue(&friction,FrictionEnum);
+	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
+	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
+	if (h[0]!=h[1])_error_("different thicknesses not supported for rift fronts");
+	thickness=h[0];
+
+	/*There is contact, we need to constrain the normal velocities (zero penetration), and the 
+	 *contact slip friction. */
+
+	/*From Peter Wriggers book (Computational Contact Mechanics, p191): */
+	Ke->values[0*numdof+0]+= +pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+1]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+2]+= -pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+3]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+
+	Ke->values[1*numdof+0]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+1]+= +pow(normal[1],2)*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+2]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+3]+= -pow(normal[1],2)*kmax*pow(10,penalty_offset);
+
+	Ke->values[2*numdof+0]+= -pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+1]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+2]+= +pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+3]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+
+	Ke->values[3*numdof+0]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+1]+= -pow(normal[1],2)*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+2]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+3]+= +pow(normal[1],2)*kmax*pow(10,penalty_offset);
+
+	/*Now take care of the friction: of type sigma=frictiontangent_velocity2-tangent_velocity1)*/
+
+	Ke->values[0*numdof+0]+= +pow(normal[1],2)*thickness*length*friction;
+	Ke->values[0*numdof+1]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[0*numdof+2]+= -pow(normal[1],2)*thickness*length*friction;
+	Ke->values[0*numdof+3]+= +normal[0]*normal[1]*thickness*length*friction;
+
+	Ke->values[1*numdof+0]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[1*numdof+1]+= +pow(normal[0],2)*thickness*length*friction;
+	Ke->values[1*numdof+2]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[1*numdof+3]+= -pow(normal[0],2)*thickness*length*friction;
+
+	Ke->values[2*numdof+0]+= -pow(normal[1],2)*thickness*length*friction;
+	Ke->values[2*numdof+1]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[2*numdof+2]+= +pow(normal[1],2)*thickness*length*friction;
+	Ke->values[2*numdof+3]+= -normal[0]*normal[1]*thickness*length*friction;
+
+	Ke->values[3*numdof+0]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[3*numdof+1]+= -pow(normal[0],2)*thickness*length*friction;
+	Ke->values[3*numdof+2]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[3*numdof+3]+= +pow(normal[0],2)*thickness*length*friction;
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Riftfront::PenaltyCreatePVectorDiagnosticHoriz {{{*/
+ElementVector* Riftfront::PenaltyCreatePVectorDiagnosticHoriz(IssmDouble kmax){
+
+	const int  numdof = NDOF2*NUMVERTICES;
+	int        j;
+	IssmDouble rho_ice;
+	IssmDouble rho_water;
+	IssmDouble gravity;
+	IssmDouble thickness;
+	IssmDouble h[2];
+	IssmDouble bed;
+	IssmDouble b[2];
+	IssmDouble pressure;
+	IssmDouble pressure_litho;
+	IssmDouble pressure_air;
+	IssmDouble pressure_melange;
+	IssmDouble pressure_water;
+	int        fill;
+	bool       shelf;
+
+	/*Objects: */
+	Tria *tria1 = NULL;
+	Tria *tria2 = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Initialize Element Matrix*/
+	if(this->active) return NULL; /*The penalty is active. No loads implied here.*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Get some inputs: */
+	this->inputs->GetInputValue(&fill,FillEnum);
+	this->inputs->GetInputValue(&shelf,SegmentOnIceShelfEnum);
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+	gravity=matpar->GetG();
+	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
+	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
+	if (h[0]!=h[1])_error_("different thicknesses not supported for rift fronts");
+	thickness=h[0];
+	tria1->GetInputValue(&b[0],nodes[0],BedEnum);
+	tria2->GetInputValue(&b[1],nodes[1],BedEnum);
+	if (b[0]!=b[1])_error_("different beds not supported for rift fronts");
+	bed=b[0];
+
+	/*Ok, this rift is opening. We should put loads on both sides of the rift flanks. Because we are dealing with contact mechanics, 
+	 * and we want to avoid zigzagging of the loads, we want lump the loads onto nodes, not onto surfaces between nodes.:*/
+
+	/*Ok, to compute the pressure, we are going to need material properties, thickness and bed for the two nodes. We assume those properties to 
+	 * be the same across the rift.: */
+
+	/*Ok, now compute the pressure (in norm) that is being applied to the flanks, depending on the type of fill: */
+	if(fill==WaterEnum){
+		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; 
+		}
+		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; 
+		}
+	}
+	else if(fill==AirEnum){
+		pressure=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)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)
+		pressure=0;
+	}
+	else if(fill==MelangeEnum){ //icefront finding itself against another icefront (pressure imbalance is fully compensated, ice vs ice)
+
+		if(!shelf) _error_("fill type " << fill << " not supported on ice sheets yet.");
+
+		pressure_litho=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2;
+		pressure_air=0;
+		pressure_melange=rho_ice*gravity*pow(fraction*thickness,(IssmDouble)2)/(IssmDouble)2;
+		pressure_water=1.0/2.0*rho_water*gravity*  ( pow(bed,2.0)-pow(rho_ice/rho_water*fraction*thickness,2.0) );
+
+		pressure=pressure_litho-pressure_air-pressure_melange-pressure_water;
+	}
+	else{
+		_error_("fill type " << fill << " not supported yet.");
+	}
+
+	/*Ok, add contribution to first node, along the normal i==0: */
+	for (j=0;j<2;j++){
+		pe->values[j]+=pressure*normal[j]*length;
+	}
+
+	/*Add contribution to second node, along the opposite normal: i==1 */
+	for (j=0;j<2;j++){
+		pe->values[2+j]+= -pressure*normal[j]*length;
+	}	
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Riftfront::Constrain {{{*/
+#define _ZIGZAGCOUNTER_
+
+int Riftfront::Constrain(int* punstable){
+
+	const int   numnodes        = 2;
+	IssmDouble      penetration;
+	int         activate;
+	int         unstable;
+	IssmDouble      vx1;
+	IssmDouble      vy1;
+	IssmDouble      vx2;
+	IssmDouble      vy2;
+	IssmDouble      fractionincrement;
+
+	/*Objects: */
+	Tria       *tria1           = NULL;
+	Tria       *tria2           = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Is this constraint frozen? In which case we don't touch: */
+	if (this->frozen){
+		*punstable=0;
+		return 1;
+	}
+
+	/*Is this rift segment state specified by user input? :*/
+	if (this->state==OpenEnum || this->state==ClosedEnum){
+
+		if(this->state==OpenEnum)this->active=0;
+		if(this->state==ClosedEnum)this->active=1;
+
+		/*this segment is like frozen, no instability here: */
+		*punstable=0;
+		return 1;
+	}
+
+	/*recover parameters: */
+	this->inputs->GetInputValue(&fractionincrement,FractionIncrementEnum);
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*activation: */
+	if(penetration<0)activate=1;
+	else  activate=0;
+
+	/*Here, we try to avoid zigzaging. When a penalty activates and deactivates for more than penalty_lock times, 
+	 * we increase the fraction of melange:*/
+	if(this->counter>this->penalty_lock){
+		/*reset counter: */
+		this->counter=0;
+		/*increase melange fraction: */
+		this->fraction+=fractionincrement;
+		if (this->fraction>1)this->fraction=(IssmDouble)1.0;
+		//_printf_("riftfront " << this->Id() << " fraction: " << this->fraction << "\n");
+	}
+
+	//Figure out stability of this penalty
+	if(this->active==activate){
+		unstable=0;
+	}
+	else{
+		unstable=1;
+		this->counter++;
+	}
+
+	//Set penalty flag
+	this->active=activate;
+
+	//if ((penetration>0) && (this->active==1))_printf_("Riftfront " << Id() << " wants to be released\n");
+
+	/*assign output pointer: */
+	*punstable=unstable;
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::FreezeConstraints{{{*/
+void   Riftfront::FreezeConstraints(void){
+
+	/*Just set frozen flag to 1: */
+	this->frozen=1;
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::IsFrozen{{{*/
+bool   Riftfront::IsFrozen(void){
+
+	/*Just set frozen flag to 1: */
+	if(this->frozen)return 1;
+	else return 0;
+}
+/*}}}*/
+/*FUNCTION Riftfront::IsMaterialStable {{{*/
+int   Riftfront::IsMaterialStable(void){
+
+	IssmDouble converged=0;
+
+	this->inputs->GetInputValue(&converged,ConvergedEnum);
+
+	if(reCast<int,IssmDouble>(converged)){
+		/*ok, material non-linearity has converged. If that was already the case, we keep 
+		 * constraining the rift front. If it was not, and this is the first time the material 
+		 * has converged, we start constraining now!: */
+		this->material_converged=1;
+	}
+
+	return this->material_converged;
+}
+/*}}}*/
+/*FUNCTION Riftfront::MaxPenetration {{{*/
+int   Riftfront::MaxPenetration(IssmDouble* ppenetration){
+
+	const int     numnodes=2;
+	IssmDouble        penetration=0;
+	IssmDouble      vx1;
+	IssmDouble      vy1;
+	IssmDouble      vx2;
+	IssmDouble      vy2;
+
+	/*Objects: */
+	Tria       *tria1           = NULL;
+	Tria       *tria2           = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	//initialize: 
+	penetration=-1;
+
+	/*recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node1 faces node2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Now, we return penetration only if we are active!: */
+	if(this->active==0)penetration=-1;
+
+	/*If we are zigzag locked, same thing: */
+	if(this->counter>this->penalty_lock)penetration=-1;
+
+	/*assign output pointer: */
+	*ppenetration=penetration;
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::Penetration {{{*/
+int   Riftfront::Penetration(IssmDouble* ppenetration){
+
+	IssmDouble    vx1;
+	IssmDouble    vy1;
+	IssmDouble    vx2;
+	IssmDouble    vy2;
+
+	IssmDouble    penetration;
+
+	/*Objects: */
+	Tria     *tria1       = NULL;
+	Tria     *tria2       = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Now, we return penetration only if we are active!: */
+	if(this->active==0)penetration=0;
+
+	/*assign output pointer: */
+	*ppenetration=penetration;
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::PotentialUnstableConstraint {{{*/
+int   Riftfront::PotentialUnstableConstraint(int* punstable){
+
+	const int   numnodes        = 2;
+	IssmDouble  penetration;
+	int         unstable;
+	IssmDouble  vx1;
+	IssmDouble  vy1;
+	IssmDouble  vx2;
+	IssmDouble  vy2;
+
+	/*Objects: */
+	Tria       *tria1 = NULL;
+	Tria       *tria2 = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Ok, we are looking for positive penetration in an active constraint: */
+	if(this->active){
+		if (penetration>=0){
+			unstable=1;
+		}
+		else{
+			unstable=0;
+		}
+	}
+	else{
+		unstable=0;
+	}
+
+	/*assign output pointer: */
+	*punstable=unstable;
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::PreConstrain {{{*/
+int   Riftfront::PreConstrain(int* punstable){
+
+	const int   numnodes    = 2;
+	IssmDouble      penetration;
+	int         unstable;
+	IssmDouble      vx1;
+	IssmDouble      vy1;
+	IssmDouble      vx2;
+	IssmDouble      vy2;
+
+	/*Objects: */
+	Tria       *tria1       = NULL;
+	Tria       *tria2       = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Ok, we are preconstraining here. Ie, anything that penetrates is constrained until stability of the entire set 
+	 * of constraints is reached.: */
+	if(penetration<0){
+		if (!this->active){
+			/*This is the first time penetration happens: */
+			this->active=1;
+			unstable=1;
+		}
+		else{
+			/*This constraint was already active: */
+			this->active=1;
+			unstable=0;
+		}
+	}
+	else{
+		/*No penetration happening. : */
+		if (!this->active){
+			/*This penalty was not active, and no penetration happening. Do nonthing: */
+			this->active=0;
+			unstable=0; 
+		}
+		else{
+			/*Ok, this penalty wants to get released. But not now, this is preconstraint, not constraint: */
+			this->active=1;
+			unstable=0;
+		}
+	}
+
+	/*assign output pointer: */
+	*punstable=unstable;
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::PreStable {{{*/
+bool  Riftfront::PreStable(){
+	return prestable;
+}
+/*}}}*/
+/*FUNCTION Riftfront::SetPreStable {{{*/
+void Riftfront::SetPreStable(){
+	prestable=1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::IsInput{{{*/
+bool Riftfront::IsInput(int name){
+	if (
+				name==ConvergedEnum ||
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==BedEnum 
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Riftfront.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Riftfront.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Loads/Riftfront.h	(revision 15396)
@@ -0,0 +1,106 @@
+/*!\file Riftfront.h
+ * \brief: header file for riftfront object
+ */
+
+#ifndef _RIFTFRONT_H_
+#define _RIFTFRONT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Load.h"
+class Hook;
+class Parameters;
+class Inputs;
+class IoModel;
+/*}}}*/
+
+class Riftfront: public Load {
+
+	public:
+		int		id;
+		int     analysis_type;
+
+		/*hooks: */
+		Hook* hnodes;
+		Hook* helements;
+		Hook* hmatpar;
+
+		/*Corresponding fields*/
+		Matpar   *matpar;
+		Node    **nodes;
+		Element **elements;
+
+		/*computational: */
+		int         penalty_lock;
+		bool        active;
+		bool        frozen;
+		int         counter;
+		bool        prestable;
+		bool        material_converged;
+		IssmDouble  normal[2];
+		IssmDouble  length;
+		IssmDouble  fraction;
+		int         state;
+
+		Parameters *parameters;           //pointer to solution parameters
+		Inputs     *inputs;
+
+		/*Riftfrontconstructors,destructors: {{{*/
+		Riftfront();
+		Riftfront(int riftfront_id,int i, IoModel* iomodel,int analysis_type);
+		~Riftfront();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*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!");}
+		void    InputUpdateFromConstant(bool constant, int name);
+		void    InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		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){_error_("Not implemented yet");};
+		void  GetNodesSidList(int* sidlist);
+		int   GetNumberOfNodes(void);
+		bool  IsPenalty(void);
+		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
+		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+		/*Riftfront specific routines: {{{*/
+		bool  PreStable();
+		ElementMatrix* PenaltyCreateKMatrixDiagnosticHoriz(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorDiagnosticHoriz(IssmDouble kmax);
+		void  SetPreStable();
+		int   PreConstrain(int* punstable);
+		int   Constrain(int* punstable);
+		void  FreezeConstraints(void);
+		bool  IsFrozen(void);
+		int   Penetration(IssmDouble* ppenetration);
+		int   MaxPenetration(IssmDouble* ppenetration);
+		int   PotentialUnstableConstraint(int* punstable);
+		int   IsMaterialStable(void);
+		bool  IsInput(int name);
+		/*}}}*/
+};
+
+#endif  /* _RIFTFRONT_H_ */
Index: /issm/trunk/src/c/classes/Materials/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Materials/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/classes/Materials/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,10 @@
+# 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 15396)
+++ /issm/trunk/src/c/classes/Materials/Matdamageice.cpp	(revision 15396)
@@ -0,0 +1,883 @@
+/*!\file Matdamageice.c
+ * \brief: implementation of the Matdamageice 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"
+
+/*Matdamageice constructors and destructor*/
+/*FUNCTION Matdamageice::Matdamageice(){{{*/
+Matdamageice::Matdamageice(){
+	this->inputs=NULL;
+	this->helement=NULL;
+	return;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::Matdamageice(int id, int index, IoModel* iomodel, int num_vertices){{{*/
+Matdamageice::Matdamageice(int matice_mid,int index, IoModel* iomodel){
+
+	/*Intermediaries:*/
+	int    matice_eid;
+
+	/*Initialize id*/
+	this->mid=matice_mid;
+
+	/*Initialize inputs*/
+	this->inputs=new Inputs();
+
+	/*Initialize inputs from IoModel*/
+	this->InputUpdateFromIoModel(index,iomodel);
+
+	/*Hooks: */
+	matice_eid=index+1;
+	this->helement=new Hook(&matice_eid,1);
+
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Matdamageice::~Matdamageice(){{{*/
+Matdamageice::~Matdamageice(){
+	delete helement;
+	delete inputs;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Matdamageice::Echo {{{*/
+void Matdamageice::Echo(void){
+
+	_printf_("Matdamageice:\n");
+	_printf_("   mid: " << mid << "\n");
+	_printf_("   inputs:\n");
+	inputs->Echo();
+	_printf_("   element:\n");
+	helement->Echo();
+}
+/*}}}*/
+/*FUNCTION Matdamageice::DeepEcho {{{*/
+void Matdamageice::DeepEcho(void){
+
+	_printf_("Matdamageice:\n");
+	_printf_("   mid: " << mid << "\n");
+	_printf_("   inputs:\n");
+	inputs->DeepEcho();
+	_printf_("   element:\n");
+	helement->Echo();
+}		
+/*}}}*/
+/*FUNCTION Matdamageice::Id {{{*/
+int    Matdamageice::Id(void){ return mid; }
+/*}}}*/
+/*FUNCTION Matdamageice::ObjectEnum{{{*/
+int Matdamageice::ObjectEnum(void){
+
+	return MatdamageiceEnum;
+
+}
+/*}}}*/
+/*FUNCTION Matdamageice::copy {{{*/
+Object* Matdamageice::copy() {
+
+	/*Output*/
+	Matdamageice* matice=NULL;
+
+	/*Initialize output*/
+	matice=new Matdamageice();
+
+	/*copy fields: */
+	matice->mid=this->mid;
+	matice->helement=(Hook*)this->helement->copy();
+	if(this->inputs) matice->inputs=(Inputs*)this->inputs->Copy();
+	else  matice->inputs=new Inputs();
+
+	return matice;
+}
+/*}}}*/
+
+/*Matdamageice management*/
+/*FUNCTION Matdamageice::Configure {{{*/
+void  Matdamageice::Configure(Elements* elementsin){
+
+	/*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: */
+	helement->configure((DataSet*)elementsin);
+}
+/*}}}*/
+/*FUNCTION Matdamageice::SetCurrentConfiguration {{{*/
+void  Matdamageice::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetA {{{*/
+IssmDouble Matdamageice::GetA(){
+	/*
+	 * A = 1/B^n
+	 */
+
+	IssmDouble B,n;
+
+	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	n=this->GetN();
+
+	return pow(B,-n);
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetB {{{*/
+IssmDouble Matdamageice::GetB(){
+
+	/*Output*/
+	IssmDouble B;
+
+	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	return B;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetBbar {{{*/
+IssmDouble Matdamageice::GetBbar(){
+
+	/*Output*/
+	IssmDouble Bbar;
+
+	inputs->GetInputAverage(&Bbar,MaterialsRheologyBbarEnum);
+	return Bbar;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetN {{{*/
+IssmDouble Matdamageice::GetN(){
+
+	/*Output*/
+	IssmDouble n;
+
+	inputs->GetInputAverage(&n,MaterialsRheologyNEnum);
+	return n;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetZ {{{*/
+IssmDouble Matdamageice::GetZ(){
+
+	/*Output*/
+	IssmDouble Z;
+
+	inputs->GetInputAverage(&Z,MaterialsRheologyZEnum);
+	return Z;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetZbar {{{*/
+IssmDouble Matdamageice::GetZbar(){
+
+	/*Output*/
+	IssmDouble Zbar;
+
+	inputs->GetInputAverage(&Zbar,MaterialsRheologyZbarEnum);
+	return Zbar;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetVectorFromInputs{{{*/
+void  Matdamageice::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
+
+	/*Intermediaries*/
+	Element *element= NULL;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that input_enum is a material input*/
+	if (!IsInput(input_enum)) return;
+
+	switch(element->ObjectEnum()){
+
+		case TriaEnum:{
+
+			/*Prepare index list*/
+			int vertexpidlist[3];
+			((Tria*)element)->GetVertexPidList(&vertexpidlist[0]);
+
+			/*Get input (either in element or material)*/
+			Input* input=inputs->GetInput(input_enum);
+			if(!input) _error_("Input " << EnumToStringx(input_enum) << " not found in material");
+
+			/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+			input->GetVectorFromInputs(vector,&vertexpidlist[0]);}
+			break;
+
+		default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosity2d {{{*/
+void  Matdamageice::GetViscosity2d(IssmDouble* pviscosity, IssmDouble* epsilon){
+	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
+												   Z * B
+	  viscosity= -------------------------------------------------------------------
+						  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+
+	  where viscosity is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	  vector, and n the flow law exponent.
+
+	  If epsilon is NULL, it means this is the first time SystemMatrices is being run, and we 
+	  return 10^14, initial viscosity.
+	  */
+
+	/*output: */
+	IssmDouble viscosity;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary: */
+	IssmDouble A,e;
+	IssmDouble Btmp,B,n,Z;
+
+	/*Get B and n*/
+	Btmp=GetBbar();
+	Z=GetZbar();
+	n=GetN();
+	B=Z*Btmp;
+
+	if (n==1){
+		/*Viscous behaviour! viscosity=B: */
+		viscosity=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
+			viscosity=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		}
+		else{
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			exy=*(epsilon+2);
+
+			/*Build viscosity: viscosity=B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+			if(A==0){
+				/*Maxiviscositym viscosity for 0 shear areas: */
+				viscosity=2.5*pow(10.,17.);
+			}
+			else{
+				e=(n-1)/(2*n);
+				viscosity=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Return: */
+	*pviscosity=viscosity;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosity3d {{{*/
+void  Matdamageice::GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* epsilon){
+
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *                                               B
+	 * viscosity3d= -------------------------------------------------------------------
+	 *                      2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	 *     vector, and n the flow law exponent.
+	 *
+	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
+	 * return g, initial viscosity.
+	 */
+
+	/*output: */
+	IssmDouble viscosity3d;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz;
+
+	/*Intermediaries: */
+	IssmDouble A,e;
+	IssmDouble B,n,Z;
+
+	/*Get B, Z and n*/
+	n=GetN();
+	Z=GetZ();
+	B=Z*GetB();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity3d=B: */
+		viscosity3d=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0)){
+			viscosity3d=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		}
+		else{
+
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			exy=*(epsilon+2);
+			exz=*(epsilon+3);
+			eyz=*(epsilon+4);
+
+			/*Build viscosity: viscosity3d=2*B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+pow(exz,2)+pow(eyz,2)+exx*eyy;
+			if(A==0){
+				/*Maxiviscosity3dm viscosity for 0 shear areas: */
+				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			}
+			else{
+				e=(n-1)/2/n;
+
+				viscosity3d=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity3d<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Assign output pointers:*/
+	*pviscosity3d=viscosity3d;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosity3dStokes {{{*/
+void  Matdamageice::GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *                                          B
+	 * viscosity3d= -------------------------------------------------------------------
+	 *                   2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	 *     vector, and n the flow law exponent.
+	 *
+	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
+	 * return g, initial viscosity.
+	 */
+
+	/*output: */
+	IssmDouble viscosity3d;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz,ezz;
+
+	/*Intermediaries: */
+	IssmDouble A,e;
+	IssmDouble B,n,Z;
+	IssmDouble eps0;
+
+	/*Get B and n*/
+	eps0=pow((IssmDouble)10,(IssmDouble)-27);
+	n=GetN();
+	Z=GetZ();
+	B=Z*GetB();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity3d=B: */
+		viscosity3d=B/2;
+	}
+	else{
+		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);
+		}
+		else{
+
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			ezz=*(epsilon+2); //not used
+			exy=*(epsilon+3);
+			exz=*(epsilon+4);
+			eyz=*(epsilon+5);
+
+			/*Build viscosity: viscosity3d=B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+pow(exz,2)+pow(eyz,2)+exx*eyy+pow(eps0,2);
+			if(A==0){
+				/*Maxiviscosity3dm viscosity for 0 shear areas: */
+				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			}
+			else{
+				e=(n-1)/2/n;
+				viscosity3d=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity3d<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Assign output pointers:*/
+	*pviscosity3d=viscosity3d;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosityComplement {{{*/
+void  Matdamageice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *  										                1
+	 * viscosity= -------------------------------------------------------------------
+	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
+	 * return mu20, initial viscosity.
+	 */
+
+	/*output: */
+	IssmDouble viscosity_complement;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary value A and exponent e: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if(epsilon){
+		exx=*(epsilon+0);
+		eyy=*(epsilon+1);
+		exy=*(epsilon+2);
+
+		/*Build viscosity: mu2=B/(2*A^e) */
+		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+		if(A==0){
+			/*Maximum viscosity_complement for 0 shear areas: */
+			viscosity_complement=2.25*pow((IssmDouble)10,(IssmDouble)17);
+		}
+		else{
+			e=(n-1)/(2*n);
+
+			viscosity_complement=1/(2*pow(A,e));
+		}
+	}
+	else{
+		viscosity_complement=4.5*pow((IssmDouble)10,(IssmDouble)17);
+	}
+
+	/*Checks in debugging mode*/
+	_assert_(B>0);
+	_assert_(n>0);
+	_assert_(viscosity_complement>0);
+
+	/*Return: */
+	*pviscosity_complement=viscosity_complement;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosityZComplement {{{*/
+void  Matdamageice::GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
+	/*Return viscosity derivative for control method d(mu)/dZ: 
+	 *
+	 *  										               B 
+	 * dviscosity= -------------------------------------------------------------------
+	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
+	 * return mu20, initial viscosity.
+	 */
+
+	/*output: */
+	IssmDouble viscosity_complement;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary value A and exponent e: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if(epsilon){
+		exx=*(epsilon+0);
+		eyy=*(epsilon+1);
+		exy=*(epsilon+2);
+
+		/*Build viscosity: mu2=B/(2*A^e) */
+		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+		if(A==0){
+			/*Maximum viscosity_complement for 0 shear areas: */
+			viscosity_complement=2.25*pow((IssmDouble)10,(IssmDouble)17);
+		}
+		else{
+			e=(n-1)/(2*n);
+
+			viscosity_complement=B/(2*pow(A,e));
+		}
+	}
+	else{
+		viscosity_complement=4.5*pow((IssmDouble)10,(IssmDouble)17);
+	}
+
+	/*Checks in debugging mode*/
+	_assert_(B>0);
+	_assert_(n>0);
+	_assert_(viscosity_complement>0);
+
+	/*Return: */
+	*pviscosity_complement=viscosity_complement;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosityDerivativeEpsSquare{{{*/
+void  Matdamageice::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+
+	/*output: */
+	IssmDouble mu_prime;
+	IssmDouble mu,n,eff2;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,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)){
+		mu_prime=0.5*pow((IssmDouble)10,(IssmDouble)14);
+	}
+	else{
+		/*Retrive strain rate components: */
+		exx=epsilon[0];
+		eyy=epsilon[1];
+		exy=epsilon[2];
+		exz=epsilon[3];
+		eyz=epsilon[4];
+		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;
+
+	/*Get visocisty and n*/
+	GetViscosity2d(&mu,epsilon);
+	n=GetN();
+
+	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
+		mu_prime=0.5*pow((IssmDouble)10,(IssmDouble)14);
+	}
+	else{
+		/*Retrive strain rate components: */
+		exx=epsilon[0];
+		eyy=epsilon[1];
+		exy=epsilon[2];
+		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy ;
+
+		mu_prime=(1-n)/(2*n) * mu/eff2;
+	}
+
+	/*Assign output pointers:*/
+	*pmu_prime=mu_prime;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputDuplicate{{{*/
+void  Matdamageice::InputDuplicate(int original_enum,int new_enum){
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
+void  Matdamageice::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+
+	/*Intermediaries*/
+	Element *element      = NULL;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			switch(element->ObjectEnum()){
+
+				case TriaEnum: {
+					IssmDouble values[3];
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->vertices[i]->Pid()];
+					this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+					return;
+				}
+				default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+}
+/*}}}*/
+/*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){
+
+	/*Intermediaries*/
+	Element *element      = NULL;
+	Parameters* parameters= NULL;
+	int         dim;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			switch(element->ObjectEnum()){
+
+				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;
+				}
+				default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromMatrixDakota(int* 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*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
+void  Matdamageice::InputUpdateFromConstant(IssmDouble constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromConstant(int constant, int name) {{{*/
+void  Matdamageice::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromConstant(bool constant, int name) {{{*/
+void  Matdamageice::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromSolution{{{*/
+void  Matdamageice::InputUpdateFromSolution(IssmDouble* solution){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromIoModel{{{*/
+void Matdamageice::InputUpdateFromIoModel(int index, IoModel* iomodel){
+
+	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){
+
+		/*Intermediaries*/
+		const int num_vertices = 3; //Tria has 3 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 TriaInput(MaterialsRheologyBbarEnum,nodeinputs,P1Enum));
+		}
+
+		/*Get n*/
+		if (iomodel->Data(MaterialsRheologyNEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
+			this->inputs->AddInput(new TriaInput(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 TriaInput(MaterialsRheologyZbarEnum,nodeinputs,P1Enum));
+		}
+
+		/*Control Inputs*/
+		#ifdef _HAVE_CONTROL_
+		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+			for(i=0;i<num_control_type;i++){
+				switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
+					case MaterialsRheologyBbarEnum:
+						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(MaterialsRheologyBbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
+					case MaterialsRheologyZbarEnum:
+						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(MaterialsRheologyZbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
+
+				}
+			}
+		}
+		#endif
+	}
+
+	/*if 3d*/
+	#ifdef _HAVE_3D_
+	else if(dim==3){
+
+		/*Intermediaries*/
+		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));
+		}
+
+		/*Get n*/
+		if (iomodel->Data(MaterialsRheologyNEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
+			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyNEnum,nodeinputs));
+		}
+
+		/*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));
+		}
+
+		/*Control Inputs*/
+		#ifdef _HAVE_CONTROL_
+		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+			for(i=0;i<num_control_type;i++){
+				switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
+					case MaterialsRheologyBbarEnum:
+						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));
+						}
+						break;
+					case MaterialsRheologyZbarEnum:
+						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));
+						}
+						break;
+				}
+			}
+		}
+		#endif
+	}
+	#endif
+	else{
+		_error_("Mesh type not supported yet!");
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::IsInput{{{*/
+bool Matdamageice::IsInput(int name){
+	if (
+				name==MaterialsRheologyBEnum ||
+				name==MaterialsRheologyBbarEnum ||
+				name==MaterialsRheologyNEnum ||
+				name==MaterialsRheologyZEnum ||
+				name==MaterialsRheologyZbarEnum
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Materials/Matdamageice.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matdamageice.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Materials/Matdamageice.h	(revision 15396)
@@ -0,0 +1,69 @@
+/*!\file Matdamageice.h
+ * \brief: header file for matice object
+ */
+
+#ifndef MATDAMAGEICE_H_
+#define MATDAMAGEICE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Material.h"
+class IoModel;
+/*}}}*/
+
+class Matdamageice: public Material{
+
+	private: 
+		int	   mid;
+		Hook* helement;
+
+	public:
+		/*Matdamageice constructors, destructors: {{{*/
+		Matdamageice();
+		Matdamageice(int mid,int i, IoModel* iomodel);
+		~Matdamageice();
+		/*}}}*/
+		/*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 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);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromSolution(IssmDouble* solution);
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		/*}}}*/
+		/*Material virtual functions resolution: {{{*/
+		void   InputDuplicate(int original_enum,int new_enum);
+		void   Configure(Elements* elements);
+		void   GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum);
+		void   SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin);
+		void   GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon);
+		void   GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon);
+		void   GetViscosity3dStokes(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   GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		IssmDouble GetA();
+		IssmDouble GetB();
+		IssmDouble GetBbar();
+		IssmDouble GetN();
+		IssmDouble GetZ();
+		IssmDouble GetZbar();
+		bool   IsInput(int name);
+		/*}}}*/
+};
+
+#endif  /* _MATICE_H_ */
Index: /issm/trunk/src/c/classes/Materials/Material.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Material.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Materials/Material.h	(revision 15396)
@@ -0,0 +1,43 @@
+/*!\file:  Material.h
+ * \brief abstract class for Material object
+ */ 
+
+#ifndef _MATERIAL_H_
+#define _MATERIAL_H_
+
+/*Headers:*/
+/*{{{*/
+class Inputs;
+template <class doubletype> class Vector;
+#include "../../datastructures/datastructures.h"
+#include "../Update.h"
+class Elements;
+/*}}}*/
+
+class Material: public Object,public Update{
+
+	public: 
+		Inputs*  inputs;
+		virtual       ~Material(){};
+		/*WARNING: input should not be public but it is an easy way to update B from T (using UpdateFromSolution) from Pentas*/
+
+		/*Numerics*/
+		virtual void       InputDuplicate(int original_enum,int new_enum)=0;
+		virtual void       Configure(Elements* elements)=0;
+		virtual void       GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum)=0;
+		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       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       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
+		virtual IssmDouble GetA()=0;
+		virtual IssmDouble GetB()=0;
+		virtual IssmDouble GetBbar()=0;
+		virtual IssmDouble GetN()=0;
+		virtual IssmDouble GetZ()=0;
+		virtual IssmDouble GetZbar()=0;
+
+};
+#endif
Index: /issm/trunk/src/c/classes/Materials/Materials.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Materials.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Materials/Materials.cpp	(revision 15396)
@@ -0,0 +1,56 @@
+/*
+ * \file Materials.cpp
+ * \brief: Implementation of Materials class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Materials.h"
+#include "./Material.h"
+#include "../../shared/shared.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Materials::Materials(){{{*/
+Materials::Materials(){
+	enum_type=MaterialsEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Materials::~Materials(){{{*/
+Materials::~Materials(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Materials::Configure{{{*/
+void Materials::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+
+	vector<Object*>::iterator object;
+	Material* material=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		material=dynamic_cast<Material*>(*object);
+		material->Configure(elements);
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION Materials::InputDuplicate{{{*/
+void Materials::InputDuplicate(int input_enum,int output_enum){
+
+	for(int i=0;i<this->Size();i++){
+		Material* material=(Material*)this->GetObjectByOffset(i);
+		material->InputDuplicate(input_enum,output_enum);
+	}
+}
Index: /issm/trunk/src/c/classes/Materials/Materials.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Materials.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Materials/Materials.h	(revision 15396)
@@ -0,0 +1,30 @@
+#ifndef _CONTAINER_MATERIALS_H_
+#define  _CONTAINER_MATERIALS_H_
+
+/*forward declarations */
+#include "../../datastructures/datastructures.h"
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+
+/*! \brief Declaration of Materials class.
+ *
+ * Declaration of Materials class.  Materials are vector lists (Containers) of Material objects.
+ */ 
+class Materials: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Materials();
+		~Materials();
+
+		/*numerics*/
+		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void  InputDuplicate(int input_enum,int output_enum);
+
+};
+
+#endif //ifndef _MATERIALS_H_
Index: /issm/trunk/src/c/classes/Materials/Matice.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 15396)
@@ -0,0 +1,801 @@
+/*!\file Matice.c
+ * \brief: implementation of the Matice object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Matice.h"
+#include "./Materials.h"
+#include "../Inputs/Input.h"
+#include "../Inputs/Inputs.h"
+#include "../Inputs/TriaInput.h"
+#include "../Inputs/PentaP1Input.h"
+#include "../Inputs/ControlInput.h"
+#include "../Elements/Element.h"
+#include "../Elements/Tria.h"
+#include "../Elements/Penta.h"
+#include "../Params/Parameters.h"
+#include "../Vertex.h"
+#include "../Hook.h"
+#include "../Node.h"
+#include "../IoModel.h"
+#include "../../shared/shared.h"
+
+/*Matice constructors and destructor*/
+/*FUNCTION Matice::Matice(){{{*/
+Matice::Matice(){
+	this->inputs=NULL;
+	this->helement=NULL;
+	return;
+}
+/*}}}*/
+/*FUNCTION Matice::Matice(int id, int index, IoModel* iomodel, int num_vertices){{{*/
+Matice::Matice(int matice_mid,int index, IoModel* iomodel){
+
+	/*Intermediaries:*/
+	int    matice_eid;
+
+	/*Initialize id*/
+	this->mid=matice_mid;
+
+	/*Initialize inputs*/
+	this->inputs=new Inputs();
+
+	/*Initialize inputs from IoModel*/
+	this->InputUpdateFromIoModel(index,iomodel);
+
+	/*Hooks: */
+	matice_eid=index+1;
+	this->helement=new Hook(&matice_eid,1);
+
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Matice::~Matice(){{{*/
+Matice::~Matice(){
+	delete helement;
+	delete inputs;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Matice::Echo {{{*/
+void Matice::Echo(void){
+
+	_printf_("Matice:\n");
+	_printf_("   mid: " << mid << "\n");
+	_printf_("   inputs:\n");
+	inputs->Echo();
+	_printf_("   element:\n");
+	helement->Echo();
+}
+/*}}}*/
+/*FUNCTION Matice::DeepEcho {{{*/
+void Matice::DeepEcho(void){
+
+	_printf_("Matice:\n");
+	_printf_("   mid: " << mid << "\n");
+	_printf_("   inputs:\n");
+	inputs->DeepEcho();
+	_printf_("   element:\n");
+	helement->Echo();
+}		
+/*}}}*/
+/*FUNCTION Matice::Id {{{*/
+int    Matice::Id(void){ return mid; }
+/*}}}*/
+/*FUNCTION Matice::ObjectEnum{{{*/
+int Matice::ObjectEnum(void){
+
+	return MaticeEnum;
+
+}
+/*}}}*/
+/*FUNCTION Matice::copy {{{*/
+Object* Matice::copy() {
+
+	/*Output*/
+	Matice* matice=NULL;
+
+	/*Initialize output*/
+	matice=new Matice();
+
+	/*copy fields: */
+	matice->mid=this->mid;
+	matice->helement=(Hook*)this->helement->copy();
+	if(this->inputs) matice->inputs=(Inputs*)this->inputs->Copy();
+	else  matice->inputs=new Inputs();
+
+	return matice;
+}
+/*}}}*/
+
+/*Matice management*/
+/*FUNCTION Matice::Configure {{{*/
+void  Matice::Configure(Elements* elementsin){
+
+	/*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: */
+	helement->configure((DataSet*)elementsin);
+}
+/*}}}*/
+/*FUNCTION Matice::SetCurrentConfiguration {{{*/
+void  Matice::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Matice::GetA {{{*/
+IssmDouble Matice::GetA(){
+	/*
+	 * A = 1/B^n
+	 */
+
+	IssmDouble B,n;
+
+	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	n=this->GetN();
+
+	return pow(B,-n);
+}
+/*}}}*/
+/*FUNCTION Matice::GetB {{{*/
+IssmDouble Matice::GetB(){
+
+	/*Output*/
+	IssmDouble B;
+
+	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	return B;
+}
+/*}}}*/
+/*FUNCTION Matice::GetBbar {{{*/
+IssmDouble Matice::GetBbar(){
+
+	/*Output*/
+	IssmDouble Bbar;
+
+	inputs->GetInputAverage(&Bbar,MaterialsRheologyBbarEnum);
+	return Bbar;
+}
+/*}}}*/
+/*FUNCTION Matice::GetN {{{*/
+IssmDouble Matice::GetN(){
+
+	/*Output*/
+	IssmDouble n;
+
+	inputs->GetInputAverage(&n,MaterialsRheologyNEnum);
+	return n;
+}
+/*}}}*/
+/*FUNCTION Matice::GetVectorFromInputs{{{*/
+void  Matice::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
+
+	/*Intermediaries*/
+	Element *element= NULL;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that input_enum is a material input*/
+	if (!IsInput(input_enum)) return;
+
+	switch(element->ObjectEnum()){
+
+		case TriaEnum:{
+
+							  /*Prepare index list*/
+							  int vertexpidlist[3];
+							  ((Tria*)element)->GetVertexPidList(&vertexpidlist[0]);
+
+								 /*Get input (either in element or material)*/
+								 Input* input=inputs->GetInput(input_enum);
+							  if(!input) _error_("Input " << EnumToStringx(input_enum) << " not found in material");
+
+							  /*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+							  input->GetVectorFromInputs(vector,&vertexpidlist[0]);}
+						break;
+
+		default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity2d {{{*/
+void  Matice::GetViscosity2d(IssmDouble* pviscosity, IssmDouble* epsilon){
+	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
+												    B
+	  viscosity= -------------------------------------------------------------------
+						  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+
+	  where viscosity is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	  vector, and n the flow law exponent.
+
+	  If epsilon is NULL, it means this is the first time SystemMatrices is being run, and we 
+	  return 10^14, initial viscosity.
+	  */
+
+	/*output: */
+	IssmDouble viscosity;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity=B: */
+		viscosity=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
+			viscosity=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		}
+		else{
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			exy=*(epsilon+2);
+
+			/*Build viscosity: viscosity=B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+			if(A==0){
+				/*Maxiviscositym viscosity for 0 shear areas: */
+				viscosity=2.5*pow(10.,17.);
+			}
+			else{
+				e=(n-1)/(2*n);
+				viscosity=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Return: */
+	*pviscosity=viscosity;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity3d {{{*/
+void  Matice::GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* epsilon){
+
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *                                               B
+	 * viscosity3d= -------------------------------------------------------------------
+	 *                      2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	 *     vector, and n the flow law exponent.
+	 *
+	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
+	 * return g, initial viscosity.
+	 */
+
+	/*output: */
+	IssmDouble viscosity3d;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz;
+
+	/*Intermediaries: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetB();
+	n=GetN();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity3d=B: */
+		viscosity3d=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0)){
+			viscosity3d=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		}
+		else{
+
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			exy=*(epsilon+2);
+			exz=*(epsilon+3);
+			eyz=*(epsilon+4);
+
+			/*Build viscosity: viscosity3d=2*B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+pow(exz,2)+pow(eyz,2)+exx*eyy;
+			if(A==0){
+				/*Maxiviscosity3dm viscosity for 0 shear areas: */
+				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			}
+			else{
+				e=(n-1)/2/n;
+
+				viscosity3d=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity3d<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Assign output pointers:*/
+	*pviscosity3d=viscosity3d;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity3dStokes {{{*/
+void  Matice::GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *                                          B
+	 * viscosity3d= -------------------------------------------------------------------
+	 *                   2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	 *     vector, and n the flow law exponent.
+	 *
+	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
+	 * return g, initial viscosity.
+	 */
+
+	/*output: */
+	IssmDouble viscosity3d;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz,ezz;
+
+	/*Intermediaries: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+	IssmDouble eps0;
+
+	/*Get B and n*/
+	eps0=pow((IssmDouble)10,(IssmDouble)-27);
+	B=GetB();
+	n=GetN();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity3d=B: */
+		viscosity3d=B/2;
+	}
+	else{
+		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);
+		}
+		else{
+
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			ezz=*(epsilon+2); //not used
+			exy=*(epsilon+3);
+			exz=*(epsilon+4);
+			eyz=*(epsilon+5);
+
+			/*Build viscosity: viscosity3d=B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+pow(exz,2)+pow(eyz,2)+exx*eyy+pow(eps0,2);
+			if(A==0){
+				/*Maxiviscosity3dm viscosity for 0 shear areas: */
+				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			}
+			else{
+				e=(n-1)/2/n;
+				viscosity3d=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity3d<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Assign output pointers:*/
+	*pviscosity3d=viscosity3d;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosityComplement {{{*/
+void  Matice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *  										                1
+	 * viscosity= -------------------------------------------------------------------
+	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
+	 * return mu20, initial viscosity.
+	 */
+
+	/*output: */
+	IssmDouble viscosity_complement;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary value A and exponent e: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if(epsilon){
+		exx=*(epsilon+0);
+		eyy=*(epsilon+1);
+		exy=*(epsilon+2);
+
+		/*Build viscosity: mu2=B/(2*A^e) */
+		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+		if(A==0){
+			/*Maximum viscosity_complement for 0 shear areas: */
+			viscosity_complement=2.25*pow((IssmDouble)10,(IssmDouble)17);
+		}
+		else{
+			e=(n-1)/(2*n);
+
+			viscosity_complement=1/(2*pow(A,e));
+		}
+	}
+	else{
+		viscosity_complement=4.5*pow((IssmDouble)10,(IssmDouble)17);
+	}
+
+	/*Checks in debugging mode*/
+	_assert_(B>0);
+	_assert_(n>0);
+	_assert_(viscosity_complement>0);
+
+	/*Return: */
+	*pviscosity_complement=viscosity_complement;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosityDerivativeEpsSquare{{{*/
+void  Matice::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+
+	/*output: */
+	IssmDouble mu_prime;
+	IssmDouble mu,n,eff2;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,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)){
+		mu_prime=0.5*pow((IssmDouble)10,(IssmDouble)14);
+	}
+	else{
+		/*Retrive strain rate components: */
+		exx=epsilon[0];
+		eyy=epsilon[1];
+		exy=epsilon[2];
+		exz=epsilon[3];
+		eyz=epsilon[4];
+		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;
+
+	/*Get visocisty and n*/
+	GetViscosity2d(&mu,epsilon);
+	n=GetN();
+
+	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
+		mu_prime=0.5*pow((IssmDouble)10,(IssmDouble)14);
+	}
+	else{
+		/*Retrive strain rate components: */
+		exx=epsilon[0];
+		eyy=epsilon[1];
+		exy=epsilon[2];
+		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy ;
+
+		mu_prime=(1-n)/(2*n) * mu/eff2;
+	}
+
+	/*Assign output pointers:*/
+	*pmu_prime=mu_prime;
+}
+/*}}}*/
+/*FUNCTION Matice::InputDuplicate{{{*/
+void  Matice::InputDuplicate(int original_enum,int new_enum){
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
+void  Matice::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+
+	/*Intermediaries*/
+	Element *element      = NULL;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			switch(element->ObjectEnum()){
+
+				case TriaEnum: {
+					IssmDouble values[3];
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->vertices[i]->Pid()];
+					this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+					return;
+				}
+				#ifdef _HAVE_3D_
+				case PentaEnum: {
+					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));
+					return;
+				}
+			  	#endif
+				default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		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*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
+void  Matice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
+
+	/*Intermediaries*/
+	Element *element      = NULL;
+	Parameters* parameters= NULL;
+	int         dim;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			switch(element->ObjectEnum()){
+
+				case TriaEnum: {
+					IssmDouble values[3];
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->vertices[i]->Sid()]; //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){
+							/*Duplicate rheology input: */
+							this->inputs->AddInput(new TriaInput(MaterialsRheologyBbarEnum,values,P1Enum));
+						}
+					}
+					/*}}}*/
+					return;
+				}
+				#ifdef _HAVE_3D_
+				case PentaEnum:{
+					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));
+					return;
+				}
+				# endif
+				default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromMatrixDakota(int* vector, int name, int type) {{{*/
+void  Matice::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*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){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromConstant(int constant, int name) {{{*/
+void  Matice::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromConstant(bool constant, int name) {{{*/
+void  Matice::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromSolution{{{*/
+void  Matice::InputUpdateFromSolution(IssmDouble* solution){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromIoModel{{{*/
+void Matice::InputUpdateFromIoModel(int index, IoModel* iomodel){
+
+	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){
+
+		/*Intermediaries*/
+		const int num_vertices = 3; //Tria has 3 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 TriaInput(MaterialsRheologyBbarEnum,nodeinputs,P1Enum));
+		}
+
+		/*Get n*/
+		if (iomodel->Data(MaterialsRheologyNEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
+			this->inputs->AddInput(new TriaInput(MaterialsRheologyNEnum,nodeinputs,P1Enum));
+		}
+
+		/*Control Inputs*/
+		#ifdef _HAVE_CONTROL_
+		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+			for(i=0;i<num_control_type;i++){
+				switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
+					case MaterialsRheologyBbarEnum:
+						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(MaterialsRheologyBbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
+				}
+			}
+		}
+		#endif
+	}
+
+	/*if 3d*/
+	#ifdef _HAVE_3D_
+	else if(dim==3){
+
+		/*Intermediaries*/
+		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));
+		}
+
+		/*Get n*/
+		if (iomodel->Data(MaterialsRheologyNEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
+			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyNEnum,nodeinputs));
+		}
+
+		/*Control Inputs*/
+		#ifdef _HAVE_CONTROL_
+		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+			for(i=0;i<num_control_type;i++){
+				switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
+					case MaterialsRheologyBbarEnum:
+						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));
+						}
+						break;
+				}
+			}
+		}
+		#endif
+	}
+	#endif
+	else{
+		_error_("Mesh type not supported yet!");
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Matice::IsInput{{{*/
+bool Matice::IsInput(int name){
+	if (
+				name==MaterialsRheologyBEnum ||
+				name==MaterialsRheologyBbarEnum ||
+				name==MaterialsRheologyNEnum ||
+				name==QmuMaterialsRheologyBEnum
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Materials/Matice.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matice.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Materials/Matice.h	(revision 15396)
@@ -0,0 +1,76 @@
+/*!\file Matice.h
+ * \brief: header file for matice object
+ */
+
+#ifndef MATICE_H_
+#define MATICE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Material.h"
+#include "../Hook.h"
+class IoModel;
+class Elements;
+class Loads;
+class Nodes;
+class Vertices;
+class Materials;
+class Parameters;
+/*}}}*/
+
+class Matice: public Material{
+
+	private: 
+		int   mid;
+		Hook *helement;
+
+	public:
+		/*Matice constructors, destructors: {{{*/
+		Matice();
+		Matice(int mid,int i, IoModel* iomodel);
+		~Matice();
+		/*}}}*/
+		/*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 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);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromSolution(IssmDouble* solution);
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		/*}}}*/
+		/*Material virtual functions resolution: {{{*/
+		void   InputDuplicate(int original_enum,int new_enum);
+		void   Configure(Elements* elements);
+		void   GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum);
+		void       SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void       GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon);
+		void       GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon);
+		void       GetViscosity3dStokes(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       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		IssmDouble GetA();
+		IssmDouble GetB();
+		IssmDouble GetBbar();
+		IssmDouble GetZ(){_error_("not supported");};
+		IssmDouble GetZbar(){_error_("not supported");};
+		IssmDouble GetN();
+		bool       IsInput(int name);
+		/*}}}*/
+};
+
+#endif  /* _MATICE_H_ */
Index: /issm/trunk/src/c/classes/Materials/Matpar.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 15396)
@@ -0,0 +1,469 @@
+/*!\file Matpar.c
+ * \brief: implementation of the Matpar 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"
+
+/*Matpar constructors and destructor*/
+/*FUNCTION Matpar::Matpar() {{{*/
+Matpar::Matpar(){
+	return;
+}
+/*}}}*/
+/*FUNCTION Matpar::Matpar(int matpar_mid,IoModel* iomodel){{{*/
+Matpar::Matpar(int matpar_mid, IoModel* iomodel){
+
+	bool ispdd;
+	bool isefficientlayer;
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	iomodel->Constant(&ispdd,SurfaceforcingsIspddEnum);
+
+	this->mid = matpar_mid;
+	iomodel->Constant(&this->rho_ice,MaterialsRhoIceEnum);
+	iomodel->Constant(&this->rho_water,MaterialsRhoWaterEnum);
+	iomodel->Constant(&this->rho_freshwater,MaterialsRhoFreshwaterEnum);
+	iomodel->Constant(&this->mu_water,MaterialsMuWaterEnum);
+	iomodel->Constant(&this->heatcapacity,MaterialsHeatcapacityEnum);
+	iomodel->Constant(&this->thermalconductivity,MaterialsThermalconductivityEnum);
+	iomodel->Constant(&this->latentheat,MaterialsLatentheatEnum);
+	iomodel->Constant(&this->beta,MaterialsBetaEnum);
+	iomodel->Constant(&this->meltingpoint,MaterialsMeltingpointEnum);
+	iomodel->Constant(&this->referencetemperature,ConstantsReferencetemperatureEnum);
+	iomodel->Constant(&this->mixed_layer_capacity,MaterialsMixedLayerCapacityEnum);
+	iomodel->Constant(&this->thermal_exchange_velocity,MaterialsThermalExchangeVelocityEnum);
+	iomodel->Constant(&this->g,ConstantsGEnum);
+
+	if(ispdd){
+		iomodel->Constant(&this->desfac,SurfaceforcingsDesfacEnum);
+		iomodel->Constant(&this->s0p,SurfaceforcingsS0pEnum);
+	}
+
+	if(hydrology_model==HydrologyshreveEnum){
+		iomodel->Constant(&this->hydro_CR,HydrologyshreveCREnum);
+		iomodel->Constant(&this->hydro_kn,HydrologyshreveKnEnum);
+		iomodel->Constant(&this->hydro_n,HydrologyshreveNEnum);
+		iomodel->Constant(&this->hydro_p,HydrologyshrevePEnum);
+		iomodel->Constant(&this->hydro_q,HydrologyshreveQEnum);
+	}
+	else if(hydrology_model==HydrologydcEnum){
+		iomodel->Constant(&this->sediment_compressibility,HydrologydcSedimentCompressibilityEnum);
+		iomodel->Constant(&this->sediment_porosity,HydrologydcSedimentPorosityEnum);
+		iomodel->Constant(&this->sediment_thickness,HydrologydcSedimentThicknessEnum);
+		iomodel->Constant(&this->sediment_transmitivity,HydrologydcSedimentTransmitivityEnum);
+		iomodel->Constant(&this->water_compressibility,HydrologydcWaterCompressibilityEnum);
+		iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+
+		if(isefficientlayer){
+				iomodel->Constant(&this->epl_compressibility,HydrologydcEplCompressibilityEnum);
+				iomodel->Constant(&this->epl_porosity,HydrologydcEplPorosityEnum);
+				iomodel->Constant(&this->epl_thickness,HydrologydcEplThicknessEnum);
+				iomodel->Constant(&this->epl_transmitivity,HydrologydcEplTransmitivityEnum);
+		}
+	}
+	else{
+		_error_("Hydrology model "<<EnumToStringx(hydrology_model)<<" not supported yet");
+	}
+
+	/*gia: */
+	iomodel->Constant(&this->lithosphere_shear_modulus,MaterialsLithosphereShearModulusEnum);
+	iomodel->Constant(&this->lithosphere_density,MaterialsLithosphereDensityEnum);
+	iomodel->Constant(&this->mantle_shear_modulus,MaterialsMantleShearModulusEnum);
+	iomodel->Constant(&this->mantle_density,MaterialsMantleDensityEnum);
+
+	this->inputs=NULL; /*not used here*/
+}
+/*}}}*/
+/*FUNCTION Matpar::~Matpar() {{{*/
+Matpar::~Matpar(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Matpar::Echo {{{*/
+void Matpar::Echo(void){
+
+	_printf_("Matpar:\n");
+	_printf_("   mid: " << mid << "\n");
+	_printf_("   rho_ice: " << rho_ice << "\n");
+	_printf_("   rho_water: " << rho_water << "\n");
+	_printf_("   rho_freshwater: " << rho_freshwater << "\n");
+	_printf_("   mu_water: " << mu_water << "\n");
+	_printf_("   heatcapacity: " << heatcapacity << "\n");
+	_printf_("   thermalconductivity: " << thermalconductivity << "\n");
+	_printf_("   latentheat: " << latentheat << "\n");
+	_printf_("   beta: " << beta << "\n");
+	_printf_("   meltingpoint: " << meltingpoint << "\n");
+	_printf_("   referencetemperature: " << referencetemperature << "\n");
+	_printf_("   mixed_layer_capacity: " << mixed_layer_capacity << "\n");
+	_printf_("   thermal_exchange_velocity: " << thermal_exchange_velocity << "\n");
+	_printf_("   g: " << g << "\n");
+	_printf_("   desfac: " << desfac << "\n");
+	_printf_("   s0p: " << s0p << "\n");
+	return;
+}
+/*}}}*/
+/*FUNCTION Matpar::DeepEcho {{{*/
+void Matpar::DeepEcho(void){
+
+	this->Echo();
+}		
+/*}}}*/
+/*FUNCTION Matpar::Id {{{*/
+int    Matpar::Id(void){ return mid; }
+/*}}}*/
+/*FUNCTION Matpar::ObjectEnum{{{*/
+int Matpar::ObjectEnum(void){
+
+	return MatparEnum;
+
+}
+/*}}}*/
+/*FUNCTION Matpar::copy {{{*/
+Object* Matpar::copy() {
+	return new Matpar(*this); 
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+/*FUNCTION Matpar::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
+void   Matpar::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*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){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*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) {{{*/
+void  Matpar::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
+void   Matpar::InputUpdateFromConstant(IssmDouble constant, int name){
+
+	switch(name){
+		case MaterialsRhoIceEnum:
+			this->rho_ice=constant;
+			break;
+		case MaterialsRhoWaterEnum:
+			this->rho_water=constant;
+			break;
+		case MaterialsRhoFreshwaterEnum:
+			this->rho_freshwater=constant;
+			break;
+		case MaterialsMuWaterEnum:
+			this->mu_water=constant;
+			break;
+		case MaterialsHeatcapacityEnum:
+			this->heatcapacity=constant;
+			break;
+		case MaterialsThermalconductivityEnum:
+			this->thermalconductivity=constant;
+			break;
+		case  MaterialsLatentheatEnum:
+			this->latentheat=constant;
+			break;
+		case  MaterialsBetaEnum:
+			this->beta=constant;
+			break;
+		case  MaterialsMeltingpointEnum:
+			this->meltingpoint=constant;
+			break;
+		case  ConstantsReferencetemperatureEnum:
+			this->referencetemperature=constant;
+			break;
+		case  MaterialsMixedLayerCapacityEnum:
+			this->mixed_layer_capacity=constant;
+			break;
+		case  MaterialsThermalExchangeVelocityEnum:
+			this->thermalconductivity=constant;
+			break;
+		case  ConstantsGEnum:
+			this->g=constant;
+			break;
+  	        case  SurfaceforcingsDesfacEnum:
+			this->desfac=constant;
+			break;
+		case SurfaceforcingsS0pEnum:
+			this->s0p=constant;
+			break;
+		default: 
+			break;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromConstant(int constant, int name) {{{*/
+void   Matpar::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromConstant(bool constant, int name) {{{*/
+void   Matpar::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromSolution{{{*/
+void   Matpar::InputUpdateFromSolution(IssmDouble* solution){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+
+/*Matpar management: */
+/*FUNCTION Matpar::InputDuplicate{{{*/
+void  Matpar::InputDuplicate(int original_enum,int new_enum){
+
+	   /*Call inputs method*/
+	   if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Matpar::Configure {{{*/
+void  Matpar::Configure(Elements* elementsin){
+
+	/*nothing done yet!*/
+
+}
+/*}}}*/
+/*FUNCTION Matpar::GetBeta {{{*/
+IssmDouble Matpar::GetBeta(){
+	return beta;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetG {{{*/
+IssmDouble Matpar::GetG(){
+	return g;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetHeatCapacity {{{*/
+IssmDouble Matpar::GetHeatCapacity(){
+	return heatcapacity;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetLatentHeat {{{*/
+IssmDouble Matpar::GetLatentHeat(){
+	return latentheat;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetMeltingPoint {{{*/
+IssmDouble Matpar::GetMeltingPoint(){
+	return meltingpoint;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetReferenceTemperature {{{*/
+IssmDouble Matpar::GetReferenceTemperature(){
+	return referencetemperature;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetMixedLayerCapacity {{{*/
+IssmDouble Matpar::GetMixedLayerCapacity(){
+	return mixed_layer_capacity;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetRhoIce {{{*/
+IssmDouble Matpar::GetRhoIce(){
+
+	return rho_ice;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetRhoWater {{{*/
+IssmDouble Matpar::GetRhoWater(){
+	return rho_water;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetRhoFreshwater {{{*/
+IssmDouble Matpar::GetRhoFreshwater(){
+	return rho_freshwater;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetMuWater {{{*/
+IssmDouble Matpar::GetMuWater(){
+	return mu_water;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetDesFac {{{*/
+IssmDouble Matpar::GetDesFac(){
+	return desfac;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetS0p {{{*/
+IssmDouble Matpar::GetS0p(){
+	return s0p;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetThermalConductivity {{{*/
+IssmDouble Matpar::GetThermalConductivity(){
+	return thermalconductivity;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetThermalExchangeVelocity {{{*/
+IssmDouble Matpar::GetThermalExchangeVelocity(){
+	return thermal_exchange_velocity;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetHydrologyKn {{{*/
+IssmDouble Matpar::GetHydrologyKn(){
+	return hydro_kn;		 
+}		 
+/*}}}*/			 
+/*FUNCTION Matpar::GetHydrologyP {{{*/			 
+IssmDouble Matpar::GetHydrologyP(){		 
+	return hydro_p;			 
+}		 
+/*}}}*/			 
+/*FUNCTION Matqar::GetHydrologyQ {{{*/			 
+IssmDouble Matpar::GetHydrologyQ(){		 
+	return hydro_q;			 
+}		 
+/*}}}*/			 
+/*FUNCTION Matpar::GetHydrologyCR {{{*/		 
+IssmDouble Matpar::GetHydrologyCR(){		 
+	return hydro_CR;		 
+}		 
+/*}}}*/			 
+/*FUNCTION Matpar::GetHydrologyN {{{*/			 
+IssmDouble Matpar::GetHydrologyN(){		 
+	return hydro_n;			 
+}		 
+/*}}}*/ 
+/*FUNCTION Matpar::GetSedimentStoring {{{*/
+IssmDouble Matpar::GetSedimentStoring(){
+	return this->rho_freshwater* this->g* this->sediment_porosity* this->sediment_thickness*
+    ( this->water_compressibility+( this->sediment_compressibility/ this->sediment_porosity));		 
+}		 
+/*}}}*/ 
+/*FUNCTION Matpar::GetEplStoring {{{*/
+IssmDouble Matpar::GetEplStoring(){
+	return this->rho_freshwater* this->g* this->epl_porosity* this->epl_thickness*
+    ( this->water_compressibility+( this->epl_compressibility/ this->epl_porosity));		 
+}		 
+/*}}}*/ 
+/*FUNCTION Matpar::GetSedimentTransitivity {{{*/
+IssmDouble Matpar::GetSedimentTransmitivity(){
+	return sediment_transmitivity;		 
+}		 
+/*}}}*/ 
+/*FUNCTION Matpar::GetSedimentThickness {{{*/
+IssmDouble Matpar::GetSedimentThickness(){
+	return sediment_thickness;		 
+}		 
+/*}}}*/ 
+/*FUNCTION Matpar::GetEplTransitivity {{{*/
+IssmDouble Matpar::GetEplTransmitivity(){
+	return epl_transmitivity;		 
+}		 
+/*}}}*/			 
+/*FUNCTION Matpar::TMeltingPoint {{{*/
+IssmDouble Matpar::TMeltingPoint(IssmDouble pressure){
+	return meltingpoint-beta*pressure;
+}
+/*}}}*/
+/*FUNCTION Matpar::PureIceEnthalpy{{{*/
+IssmDouble Matpar::PureIceEnthalpy(IssmDouble pressure){
+	return heatcapacity*(TMeltingPoint(pressure)-referencetemperature);
+}
+/*}}}*/
+/*FUNCTION Matpar::GetEnthalpyDiffusionParameter{{{*/
+IssmDouble Matpar::GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){
+	if(enthalpy<PureIceEnthalpy(pressure)){
+		return thermalconductivity/(rho_ice*heatcapacity);
+	}
+	else{
+		return 0.1*thermalconductivity/(rho_ice*heatcapacity);
+	}
+}
+/*}}}*/
+/*FUNCTION Matpar::EnthalpyToThermal {{{*/
+void Matpar::EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure){
+
+	/*Ouput*/
+	IssmDouble temperature,waterfraction;
+
+	if(enthalpy<PureIceEnthalpy(pressure)){
+		temperature=referencetemperature+enthalpy/heatcapacity;
+		waterfraction=0;
+	}
+	else{
+		temperature=TMeltingPoint(pressure);
+		waterfraction=(enthalpy-PureIceEnthalpy(pressure))/latentheat;
+	}
+
+	/*Assign output pointers:*/
+	*pwaterfraction=waterfraction;
+	*ptemperature=temperature;
+}
+/*}}}*/
+/*FUNCTION Matpar::ThermalToEnthalpy {{{*/
+void Matpar::ThermalToEnthalpy(IssmDouble * penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){
+
+	/*Ouput*/
+	IssmDouble enthalpy;
+
+	if(temperature<TMeltingPoint(pressure)){
+		enthalpy=heatcapacity*(temperature-referencetemperature);
+	}
+	else{
+		enthalpy=PureIceEnthalpy(pressure)+latentheat*waterfraction;
+	}
+
+	/*Assign output pointers:*/
+	*penthalpy=enthalpy;
+}
+/*}}}*/
+
+/*FUNCTION Matpar::GetLithosphereShearModulus {{{*/			 
+IssmDouble Matpar::GetLithosphereShearModulus(){		 
+	return lithosphere_shear_modulus;			 
+}		 
+/*}}}*/ 
+/*FUNCTION Matpar::GetLithosphereDensity {{{*/			 
+IssmDouble Matpar::GetLithosphereDensity(){		 
+	return lithosphere_density;			 
+}		 
+/*}}}*/ 
+/*FUNCTION Matpar::GetMantleDensity {{{*/			 
+IssmDouble Matpar::GetMantleDensity(){		 
+	return mantle_density;			 
+}		 
+/*}}}*/ 
+/*FUNCTION Matpar::GetMantleShearModulus {{{*/			 
+IssmDouble Matpar::GetMantleShearModulus(){		 
+	return mantle_shear_modulus;			 
+}		 
+/*}}}*/ 
+/*FUNCTION Matpar::IsInput{{{*/
+bool Matpar::IsInput(int name){
+	return false;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Materials/Matpar.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matpar.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Materials/Matpar.h	(revision 15396)
@@ -0,0 +1,143 @@
+/*!\file Matpar.h
+ * \brief: header file for matpar object
+ */
+
+#ifndef _MATPAR_H_
+#define _MATPAR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Material.h"
+class IoModel;
+/*}}}*/
+
+class Matpar: public Material{
+
+	private: 
+		int	  mid;
+		IssmDouble  rho_ice; 
+		IssmDouble  rho_water;
+		IssmDouble  rho_freshwater;
+		IssmDouble  mu_water;
+		IssmDouble  heatcapacity;
+		IssmDouble  thermalconductivity;
+		IssmDouble  latentheat;
+		IssmDouble  beta;
+		IssmDouble  meltingpoint;
+		IssmDouble  referencetemperature;
+		IssmDouble  mixed_layer_capacity;
+		IssmDouble  thermal_exchange_velocity;
+		IssmDouble  g;
+		IssmDouble  desfac;
+		IssmDouble  s0p;
+
+		/*hydrology Shreve: */	 
+		IssmDouble  hydro_kn;			 
+		IssmDouble  hydro_p;		 
+		IssmDouble  hydro_q;		 
+		IssmDouble  hydro_CR;			 
+		IssmDouble  hydro_n; 
+
+		/*hydrology Dual Porous Continuum: */	 
+		IssmDouble  sediment_compressibility;
+		IssmDouble  sediment_porosity;	 
+		IssmDouble  sediment_thickness;
+		IssmDouble  sediment_transmitivity;	 
+		IssmDouble  water_compressibility;
+
+		IssmDouble  epl_compressibility;
+		IssmDouble  epl_porosity;	 
+		IssmDouble  epl_thickness;
+		IssmDouble  epl_transmitivity;	 
+
+		/*gia: */
+		IssmDouble lithosphere_shear_modulus;
+		IssmDouble lithosphere_density;
+		IssmDouble mantle_shear_modulus;
+		IssmDouble mantle_density;
+
+	public:
+		Matpar();
+		Matpar(int matpar_id, IoModel* iomodel);
+		~Matpar();
+
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+		/*}}}*/
+		/*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);
+		void   InputUpdateFromConstant(bool constant, int name);
+		void   InputUpdateFromSolution(IssmDouble* solution);
+		void   InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Material virtual functions resolution: {{{*/
+		void   InputDuplicate(int original_enum,int new_enum);
+		void   Configure(Elements* elements);
+		void   GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){return;}
+		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       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       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
+		IssmDouble GetA(){_error_("not supported");};
+		IssmDouble GetB(){_error_("not supported");};
+		IssmDouble GetBbar(){_error_("not supported");};
+		IssmDouble GetN(){_error_("not supported");};
+		IssmDouble GetZ(){_error_("not supported");};
+		IssmDouble GetZbar(){_error_("not supported");};
+		/*}}}*/
+		/*Numerics: {{{*/
+		IssmDouble GetG();
+		IssmDouble GetRhoIce();
+		IssmDouble GetRhoWater();
+		IssmDouble GetRhoFreshwater();
+		IssmDouble GetMuWater();
+		IssmDouble GetMixedLayerCapacity();
+		IssmDouble GetThermalExchangeVelocity();
+		IssmDouble GetHeatCapacity();
+		IssmDouble GetThermalConductivity();
+		IssmDouble GetLatentHeat();
+		IssmDouble GetBeta();
+		IssmDouble GetMeltingPoint();
+		IssmDouble GetReferenceTemperature();
+		IssmDouble GetHydrologyKn();
+		IssmDouble GetHydrologyP();
+		IssmDouble GetHydrologyQ();
+		IssmDouble GetHydrologyCR();
+		IssmDouble GetHydrologyN();
+		IssmDouble GetSedimentStoring();
+		IssmDouble GetEplStoring();
+		IssmDouble GetSedimentTransmitivity();
+		IssmDouble GetSedimentThickness();
+		IssmDouble GetEplTransmitivity();
+		IssmDouble TMeltingPoint(IssmDouble pressure);
+		IssmDouble PureIceEnthalpy(IssmDouble pressure);
+		IssmDouble GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure);
+		IssmDouble GetLithosphereShearModulus();
+		IssmDouble GetLithosphereDensity();
+		IssmDouble GetMantleShearModulus();
+		IssmDouble GetMantleDensity();
+		void   EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure);
+		void   ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure);
+		IssmDouble GetDesFac();
+		IssmDouble GetS0p(); 
+		bool       IsInput(int name);
+		/*}}}*/
+
+};
+
+#endif  /* _MATPAR_H_ */
Index: /issm/trunk/src/c/classes/Node.cpp
===================================================================
--- /issm/trunk/src/c/classes/Node.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Node.cpp	(revision 15396)
@@ -0,0 +1,1287 @@
+/*!\file Node.c
+ * \brief: implementation of the Node object
+ */
+
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./classes.h"
+#include "shared/shared.h"
+#include "modules/ModelProcessorx/ModelProcessorx.h"
+/*}}}*/
+
+/*Node constructors and destructors:*/
+/*FUNCTION Node::Node() default constructor {{{*/
+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){
+
+	/*Intermediary*/
+	int k,l;
+	int gsize;
+	int dim;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+
+	/*id: */
+	this->id            = node_id;
+	this->sid           = node_sid;
+	this->analysis_type = analysis_type;
+
+	/*Initialize coord_system: Identity matrix by default*/
+	for(k=0;k<3;k++) for(l=0;l<3;l++) this->coord_system[k][l]=0.0;
+	for(k=0;k<3;k++) this->coord_system[k][k]=1.0;
+
+	/*indexing:*/
+	DistributeNumDofs(&this->indexing,analysis_type,iomodel->Data(FlowequationVertexEquationEnum)+io_index); //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]);
+	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){
+
+		/*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){
+			/*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])){
+				this->Deactivate();
+			}
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==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(!reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
+					this->Deactivate();
+				}
+			}
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealStokesApproximationEnum && reCast<int>(iomodel->Data(FlowequationBordermacayealEnum)[io_index])){
+				if(!reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
+					for(k=1;k<=2;k++) this->FreezeDof(k);
+				}
+			}
+		}
+		/*spc all nodes on hutter*/
+		if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==HutterApproximationEnum){
+			this->Deactivate();
+		}
+	}
+	#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 || 
+				analysis_type==MeltingAnalysisEnum || 
+				analysis_type==BedSlopeAnalysisEnum || 
+				analysis_type==SurfaceSlopeAnalysisEnum || 
+				analysis_type==BalancethicknessAnalysisEnum ||
+				analysis_type==HydrologyDCInefficientAnalysisEnum ||
+				analysis_type==HydrologyDCEfficientAnalysisEnum
+				){
+		if (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]))){
+				this->Deactivate();
+			}
+		}
+	}
+
+}
+/*}}}*/
+/*FUNCTION Node::~Node(){{{*/
+Node::~Node(){
+	delete inputs;
+	delete hvertex;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*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");
+	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");
+	indexing.DeepEcho();
+	_printf_("Vertex:\n");
+	hvertex->DeepEcho();
+	_printf_("   inputs\n");
+
+}
+/*}}}*/
+/*FUNCTION Node::Id{{{*/
+int    Node::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Node::ObjectEnum{{{*/
+int Node::ObjectEnum(void){
+
+	return NodeEnum;
+
+}
+/*}}}*/
+
+/*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){
+
+	if(setenum==GsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.gsize);
+		return indexing.gdoflist[dofindex];
+	}
+	else if(setenum==FsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.fsize);
+		return indexing.fdoflist[dofindex];
+	}
+	else if(setenum==SsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.ssize);
+		return indexing.sdoflist[dofindex];
+	}
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+
+} /*}}}*/
+/*FUNCTION Node::GetDofList{{{*/
+void  Node::GetDofList(int* outdoflist,int approximation_enum,int setenum){
+	int i;
+	int count=0;
+	int count2=0;
+
+	if(approximation_enum==NoneApproximationEnum){
+		if(setenum==GsetEnum)for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=indexing.gdoflist[i];
+		if(setenum==FsetEnum)for(i=0;i<this->indexing.fsize;i++) outdoflist[i]=indexing.fdoflist[i];
+		if(setenum==SsetEnum)for(i=0;i<this->indexing.ssize;i++) outdoflist[i]=indexing.sdoflist[i];
+	}
+	else{
+
+		if(setenum==GsetEnum){
+			if(indexing.doftype){
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						outdoflist[count]=indexing.gdoflist[i];
+						count++;
+					}
+				}
+				_assert_(count); //at least one dof should be the approximation requested
+			}
+			else for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=indexing.gdoflist[i];
+		}
+		else if(setenum==FsetEnum){
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.f_set[i]){
+						if(indexing.doftype[i]==approximation_enum){
+							outdoflist[count]=indexing.fdoflist[count2];
+							count++;
+						}
+						count2++;
+					}
+				}
+			}
+			else for(i=0;i<this->indexing.fsize;i++) outdoflist[i]=indexing.fdoflist[i];
+		}
+		else if(setenum==SsetEnum){
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.s_set[i]){
+						if(indexing.doftype[i]==approximation_enum){
+							outdoflist[count]=indexing.sdoflist[count2];
+							count++;
+						}
+						count2++;
+					}
+				}
+			}
+			else for(i=0;i<this->indexing.ssize;i++) outdoflist[i]=indexing.sdoflist[i];
+		}
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+}
+/*}}}*/
+/*FUNCTION Node::GetLocalDofList{{{*/
+void  Node::GetLocalDofList(int* outdoflist,int approximation_enum,int setenum){
+	int i;
+	int count=0;
+	int count2=0;
+
+	if(approximation_enum==NoneApproximationEnum){
+		if(setenum==GsetEnum)for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=i;
+		else if(setenum==FsetEnum){
+			count=0;
+			for(i=0;i<this->indexing.gsize;i++){
+				if(indexing.f_set[i]){
+					outdoflist[count]=i;
+					count++;
+				}
+			}
+		}
+		else if(setenum==SsetEnum){
+			count=0;
+			for(i=0;i<this->indexing.gsize;i++){
+				if(indexing.s_set[i]){
+					outdoflist[count]=i;
+					count++;
+				}
+			}
+		}
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+	else{
+
+		if(setenum==GsetEnum){
+			if(indexing.doftype){
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						outdoflist[count]=count;
+						count++;
+					}
+				}
+				_assert_(count);
+			}
+			else for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=i;
+		}
+		else if(setenum==FsetEnum){
+
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						if(indexing.f_set[i]){
+							outdoflist[count]=count2;
+							count++;
+						}
+						count2++;
+					}
+				}
+				_assert_(count2);
+			}
+			else{
+
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.f_set[i]){
+						outdoflist[count]=i;
+						count++;
+					}
+				}
+			}
+		}
+		else if(setenum==SsetEnum){
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						if(indexing.s_set[i]){
+							outdoflist[count]=count2;
+							count++;
+						}
+						count2++;
+					}
+				}
+				_assert_(count2);
+			}
+			else{
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.s_set[i]){
+						outdoflist[count]=i;
+						count++;
+					}
+				}
+			}
+		}
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+}
+/*}}}*/
+/*FUNCTION Node::Sid{{{*/
+int    Node::Sid(void){ return sid; }
+/*}}}*/
+#ifdef _HAVE_DIAGNOSTIC_
+/*FUNCTION Node::GetCoordinateSystem{{{*/
+void Node::GetCoordinateSystem(IssmDouble* coord_system_out){
+
+	/*Copy coord_system*/
+	for(int k=0;k<3;k++) for(int l=0;l<3;l++) coord_system_out[3*k+l]=this->coord_system[k][l];
+
+}
+/*}}}*/
+#endif
+/*FUNCTION Node::InAnalysis{{{*/
+bool Node::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+
+/*Node numerics:*/
+/*FUNCTION Node::ApplyConstraints{{{*/
+void  Node::ApplyConstraint(int dof,IssmDouble value){
+
+	/*Dof should be added in the s set, describing which 
+	 * dofs are constrained to a certain value (dirichlet boundary condition*/
+	DofInSSet(dof-1);
+	this->indexing.svalues[dof-1]=value;
+}
+/*}}}*/
+/*FUNCTION Node::RelaxConstraint{{{*/
+void  Node::RelaxConstraint(int dof){
+
+	/*Dof should be added to the f-set, and taken out of the s-set:*/
+	DofInFSet(dof-1);
+	this->indexing.svalues[dof-1]=NAN;
+}
+/*}}}*/
+/*FUNCTION Node::CreateVecSets {{{*/
+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 value;
+
+	int i;
+
+	for(i=0;i<this->indexing.gsize;i++){
+
+		/*g set: */
+		pv_g->SetValue(indexing.gdoflist[i],gvalue,INS_VAL);
+
+		/*f set: */
+		value=(IssmDouble)this->indexing.f_set[i];
+		pv_f->SetValue(indexing.gdoflist[i],value,INS_VAL);
+
+		/*s set: */
+		value=(IssmDouble)this->indexing.s_set[i];
+		pv_s->SetValue(indexing.gdoflist[i],value,INS_VAL);
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION Node::CreateNodalConstraints{{{*/
+void  Node::CreateNodalConstraints(Vector<IssmDouble>* ys){
+
+	int i;
+	IssmDouble* values=NULL;
+	int count;
+
+	/*Recover values for s set and plug them in constraints vector: */
+	if(this->indexing.ssize){
+		values=xNew<IssmDouble>(this->indexing.ssize);
+		count=0;
+		for(i=0;i<this->indexing.gsize;i++){
+			if(this->indexing.s_set[i]){
+				values[count]=this->indexing.svalues[i];
+				_assert_(!xIsNan<IssmDouble>(values[count]));
+				count++;
+			}
+		}
+
+		/*Add values into constraint vector: */
+		ys->SetValues(this->indexing.ssize,this->indexing.sdoflist,values,INS_VAL);
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+
+}
+/*}}}*/
+/*FUNCTION Node::DofInSSet {{{*/
+void  Node::DofInSSet(int dof){
+
+	/*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;
+}
+/*}}}*/
+/*FUNCTION Node::DofInFSet {{{*/
+void  Node::DofInFSet(int dof){
+
+	/*Put dof for this node into the f set (ie, this dof will NOT be constrained 
+	 * to a fixed value during computations. */
+
+	this->indexing.f_set[dof]=1; 
+	this->indexing.s_set[dof]=0;
+}
+/*}}}*/
+/*FUNCTION Node::FreezeDof{{{*/
+void  Node::FreezeDof(int dof){
+
+	DofInSSet(dof-1); //with 0 displacement for this dof.
+
+}
+/*}}}*/
+/*FUNCTION Node::Deactivate{{{*/
+void  Node::Deactivate(void){
+
+	indexing.Deactivate();
+
+}
+/*}}}*/
+/*FUNCTION Node::Activate{{{*/
+void  Node::Activate(void){
+
+	indexing.Activate();
+
+}
+/*}}}*/
+/*FUNCTION Node::IsActive{{{*/
+bool Node::IsActive(void){
+
+	return indexing.active;
+
+}
+/*}}}*/
+/*FUNCTION Node::GetApproximation {{{*/
+int   Node::GetApproximation(){
+
+	return approximation;
+}
+/*}}}*/
+/*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){
+
+	/*Get number of degrees of freedom in a node, for a certain set (g,f or s-set)
+	 *and for a certain approximation type: */
+
+	int i;
+	int numdofs=0;
+
+	if(approximation_enum==NoneApproximationEnum){
+		if (setenum==GsetEnum) numdofs=this->indexing.gsize;
+		else if (setenum==FsetEnum) numdofs=this->indexing.fsize;
+		else if (setenum==SsetEnum) numdofs=this->indexing.ssize;
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+	else{
+		if(setenum==GsetEnum){
+			if(this->indexing.doftype){
+				numdofs=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(this->indexing.doftype[i]==approximation_enum) numdofs++;
+				}
+			}
+			else numdofs=this->indexing.gsize;
+		}
+		else if (setenum==FsetEnum){
+			if(this->indexing.doftype){
+				numdofs=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if((this->indexing.doftype[i]==approximation_enum) && (this->indexing.f_set[i])) numdofs++;
+				}
+			}
+			else numdofs=this->indexing.fsize;
+		}
+		else if (setenum==SsetEnum){
+			if(this->indexing.doftype){
+				numdofs=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if((this->indexing.doftype[i]==approximation_enum) && (this->indexing.s_set[i])) numdofs++;
+				}
+			}
+			else numdofs=this->indexing.ssize;
+		}
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+	return numdofs;
+}
+/*}}}*/
+/*FUNCTION Node::IsClone {{{*/
+int   Node::IsClone(){
+
+	return indexing.clone;
+
+}
+/*}}}*/
+/*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++){
+		if(this->indexing.s_set[i]){
+			this->indexing.svalues[i]=ys[this->indexing.sdoflist[count]];
+			count++;
+		}
+	}
+}
+/*}}}*/
+/*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;
+
+	if(setenum==FsetEnum){
+		if(this->indexing.fsize){
+			indices=xNew<int>(this->indexing.fsize);
+ 			values=xNew<IssmDouble>(this->indexing.fsize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.f_set[i]){
+					_assert_(vector_serial);
+					values[count]=vector_serial[this->indexing.fdoflist[count]];
+					indices[count]=this->indexing.gdoflist[i];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			ug->SetValues(this->indexing.fsize,indices,values,INS_VAL);
+		}
+	}
+	else if(setenum==SsetEnum){
+		if(this->indexing.ssize){
+			indices=xNew<int>(this->indexing.ssize);
+			values=xNew<IssmDouble>(this->indexing.ssize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.s_set[i]){
+					_assert_(vector_serial);
+					values[count]=vector_serial[this->indexing.sdoflist[count]];
+					indices[count]=this->indexing.gdoflist[i];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			ug->SetValues(this->indexing.ssize,indices,values,INS_VAL);
+		}
+	}
+	else _error_("VecMerge can only merge from the s or f-set onto the g-set!");
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<int>(indices);
+}
+/*}}}*/
+/*FUNCTION Node::VecReduce {{{*/
+void   Node::VecReduce(Vector<IssmDouble>* vector, IssmDouble* ug_serial,int setenum){
+
+	IssmDouble* values=NULL;
+	int     count=0;
+	int     i;
+
+	if(setenum==FsetEnum){
+		if(this->indexing.fsize){
+ 			values=xNew<IssmDouble>(this->indexing.fsize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.f_set[i]){
+					_assert_(ug_serial);
+					values[count]=ug_serial[this->indexing.gdoflist[i]];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			vector->SetValues(this->indexing.fsize,this->indexing.fdoflist,values,INS_VAL);
+		}
+	}
+	else if(setenum==SsetEnum){
+		if(this->indexing.ssize){
+			values=xNew<IssmDouble>(this->indexing.ssize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.s_set[i]){
+					_assert_(ug_serial);
+					values[count]=ug_serial[this->indexing.gdoflist[i]];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			vector->SetValues(this->indexing.ssize,this->indexing.sdoflist,values,INS_VAL);
+		}
+	}
+	else _error_("VecReduce can only merge from the s or f-set onto the g-set!");
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+
+/* indexing routines:*/
+/*FUNCTION Node::DistributeDofs{{{*/
+void  Node::DistributeDofs(int* pdofcount,int setenum){
+
+	int i;
+	int dofcount;
+
+	dofcount=*pdofcount;
+
+	/*Initialize: */
+	if(setenum==FsetEnum) this->indexing.InitSet(setenum);
+	if(setenum==SsetEnum) this->indexing.InitSet(setenum);
+
+	/*For clone nodfs, don't distribute dofs, we will get them from another cpu in UpdateCloneDofs!*/
+	if(indexing.clone){
+		return;
+	}
+
+	/*This node should distribute dofs for setenum set (eg, f_set or s_set), go ahead: */
+	if(setenum==GsetEnum){
+		for(i=0;i<this->indexing.gsize;i++){
+			indexing.gdoflist[i]=dofcount+i;
+		}
+		dofcount+=this->indexing.gsize;
+	}
+	else if(setenum==FsetEnum){
+		for(i=0;i<this->indexing.fsize;i++){
+			indexing.fdoflist[i]=dofcount+i;
+		}
+		dofcount+=this->indexing.fsize;
+	}
+	else if(setenum==SsetEnum){
+		for(i=0;i<this->indexing.ssize;i++){
+			indexing.sdoflist[i]=dofcount+i;
+		}
+		dofcount+=this->indexing.ssize;
+	}
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+
+	/*Assign output pointers: */
+	*pdofcount=dofcount;
+}
+/*}}}*/
+/*FUNCTION Node::OffsetDofs{{{*/
+void  Node::OffsetDofs(int dofcount,int setenum){
+
+	int i;
+
+	if(indexing.clone){
+		/*This node is a clone, don't off_set the dofs!: */
+		return;
+	}
+
+	/*This node should off_set the dofs, go ahead: */
+	if(setenum==GsetEnum){
+		for(i=0;i<this->indexing.gsize;i++) indexing.gdoflist[i]+=dofcount;
+	}
+	else if(setenum==FsetEnum){
+		for(i=0;i<this->indexing.fsize;i++) indexing.fdoflist[i]+=dofcount;
+	}
+	else if(setenum==SsetEnum){
+		for(i=0;i<this->indexing.ssize;i++) indexing.sdoflist[i]+=dofcount;
+	}
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Node::ShowTrueDofs{{{*/
+void  Node::ShowTrueDofs(int* truedofs, int ncols,int setenum){
+
+	int j;
+
+	/*Are we a clone? : */
+	if(indexing.clone) return;
+
+	/*Ok, we are not a clone, just plug our dofs into truedofs: */
+	switch(setenum){
+		case GsetEnum:
+			for(j=0;j<this->indexing.gsize;j++) truedofs[ncols*sid+j]=indexing.gdoflist[j];
+			break;
+		case FsetEnum:
+			for(j=0;j<this->indexing.fsize;j++) truedofs[ncols*sid+j]=indexing.fdoflist[j];
+			break;
+		case SsetEnum:
+			for(j=0;j<this->indexing.ssize;j++) truedofs[ncols*sid+j]=indexing.sdoflist[j];
+			break;
+		default:
+			_error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Node::UpdateCloneDofs{{{*/
+void  Node::UpdateCloneDofs(int* alltruedofs,int ncols,int setenum){
+
+	int j;
+
+	/*If we are not a clone, don't update, we already have dofs!: */
+	if(!indexing.clone)return;
+
+	/*Ok, we are a clone node, but we did not create the dofs for this node.
+	 *Therefore, our doflist is garbage right now. Go pick it up in the alltruedofs: */
+	switch(setenum){
+		case GsetEnum:
+			for(j=0;j<this->indexing.gsize;j++) indexing.gdoflist[j]=alltruedofs[ncols*sid+j];
+			break;
+		case FsetEnum:
+			for(j=0;j<this->indexing.fsize;j++) indexing.fdoflist[j]=alltruedofs[ncols*sid+j];
+			break;
+		case SsetEnum:
+			for(j=0;j<this->indexing.ssize;j++) indexing.sdoflist[j]=alltruedofs[ncols*sid+j];
+			break;
+		default:
+			_error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+}
+/*}}}*/
+/*FUNCTION Node::SetClone {{{*/
+void  Node::SetClone(int* minranks){
+
+	int my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if (minranks[sid]==my_rank){
+		indexing.clone=false;
+	}
+	else{
+		/*!there is a cpu with lower rank that has the same node, 
+		therefore, I am a clone*/
+		indexing.clone=true;	
+	}
+}
+/*}}}*/
+
+/*Methods inherent to Node: */
+int* GetLocalDofList(Node** nodes,int numnodes,int setenum,int approximation){ /*{{{*/
+
+	int  i,j,count,numdof,numgdof;
+	int* ndof_list=NULL;
+	int* ngdof_list_cumulative=NULL;
+	int *doflist = NULL;
+
+	if(numnodes){
+		/*allocate: */
+		ndof_list=xNew<int>(numnodes);
+		ngdof_list_cumulative=xNew<int>(numnodes);
+
+		/*Get number of dofs per node, and total for this given set*/
+		numdof=0;
+		numgdof=0;
+		for(i=0;i<numnodes;i++){
+
+			/*Cumulative list= number of dofs before node i*/
+			ngdof_list_cumulative[i]=numgdof;
+
+			/*Number of dofs for node i for given set and for the g set*/
+			ndof_list[i]=nodes[i]->GetNumberOfDofs(approximation,setenum);
+			numgdof    +=nodes[i]->GetNumberOfDofs(approximation,GsetEnum);
+			numdof     +=ndof_list[i];
+		}
+
+		if(numdof){
+			/*Allocate: */
+			doflist=xNew<int>(numdof);
+
+			/*Populate: */
+			count=0;
+			for(i=0;i<numnodes;i++){
+				nodes[i]->GetLocalDofList(&doflist[count],approximation,setenum);
+				count+=ndof_list[i];
+			}
+
+			/*We now have something like: [0 1 0 2 1 2]. Offset by gsize, to get something like: [0 1 2 4 6 7]:*/
+			count=0;
+			for(i=0;i<numnodes;i++){
+				for(j=0;j<ndof_list[i];j++){
+					doflist[count+j]+=ngdof_list_cumulative[i];
+				}
+				count+=ndof_list[i];
+			}
+		}
+		else doflist=NULL;
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(ndof_list);
+	xDelete<int>(ngdof_list_cumulative);
+
+	/*CLean-up and return*/
+	return doflist;
+}
+/*}}}*/
+int* GetGlobalDofList(Node** nodes,int numnodes,int setenum,int approximation){/*{{{*/
+
+	int  i,numdof,count;
+	int* ndof_list=NULL;
+	int *doflist = NULL;
+
+	if(numnodes){
+
+		/*Allocate:*/
+		ndof_list=xNew<int>(numnodes);
+
+		/*First, figure out size of doflist: */
+		numdof=0;
+		for(i=0;i<numnodes;i++){
+			ndof_list[i]=nodes[i]->GetNumberOfDofs(approximation,setenum);
+			numdof+=ndof_list[i];
+		}
+
+		if(numdof){
+			/*Allocate: */
+			doflist=xNew<int>(numdof);
+
+			/*Populate: */
+			count=0;
+			for(i=0;i<numnodes;i++){
+				nodes[i]->GetDofList(&doflist[count],approximation,setenum);
+				count+=ndof_list[i];
+			}
+		}
+		else doflist=NULL;
+	}
+	/*Free ressources:*/
+	xDelete<int>(ndof_list);
+
+	return doflist;
+}
+/*}}}*/
+int GetNumberOfDofs(Node** nodes,int numnodes,int setenum,int approximation){/*{{{*/
+
+	/*output: */
+	int numberofdofs=0;
+
+	for(int i=0;i<numnodes;i++){
+		numberofdofs+=nodes[i]->GetNumberOfDofs(approximation,setenum);
+	}
+
+	return numberofdofs;
+}
+/*}}}*/
+#ifdef _HAVE_DIAGNOSTIC_
+void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum){/*{{{*/
+
+	int* cs_array=NULL;
+
+	/*All nodes have the same Coordinate System*/
+	cs_array=xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
+
+	/*Call core*/
+	TransformInvStiffnessMatrixCoord(Ke,nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}
+/*}}}*/
+void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array){/*{{{*/
+
+	int     i,j;
+	int     numdofs   = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case XYEnum:   numdofs+=2; break;
+			case XYZPEnum: numdofs+=4; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current stiffness matrix*/
+	values=xNew<IssmDouble>(Ke->nrows*Ke->ncols);
+	for(i=0;i<Ke->nrows;i++) for(j=0;j<Ke->ncols;j++) values[i*Ke->ncols+j]=Ke->values[i*Ke->ncols+j];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
+
+	/*Transform matrix: R*Ke*R^T */
+	TripleMultiply(transform,numdofs,numdofs,0,
+				values,Ke->nrows,Ke->ncols,0,
+				transform,numdofs,numdofs,1,
+				&Ke->values[0],0);
+
+	/*Free Matrix*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+void TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int cs_enum){/*{{{*/
+
+	int* cs_array=NULL;
+
+	/*All nodes have the same Coordinate System*/
+	cs_array=xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
+
+	/*Call core*/
+	TransformLoadVectorCoord(pe,nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}
+/*}}}*/
+void TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array){/*{{{*/
+
+	int     i;
+	int     numdofs   = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case XYEnum:   numdofs+=2; break;
+			case XYZPEnum: numdofs+=4; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current load vector*/
+	values=xNew<IssmDouble>(pe->nrows);
+	for(i=0;i<pe->nrows;i++) values[i]=pe->values[i];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
+
+	/*Transform matrix: R^T*pe */
+	MatrixMultiply(transform,numdofs,numdofs,1,
+				values,pe->nrows,1,0,
+				&pe->values[0],0);
+
+	/*Free Matrices*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+void TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int cs_enum){/*{{{*/
+
+	int* cs_array=NULL;
+
+	/*All nodes have the same Coordinate System*/
+	cs_array=xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
+
+	/*Call core*/
+	TransformSolutionCoord(solution,nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}
+/*}}}*/
+void TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int* cs_array){/*{{{*/
+
+	int     i;
+	int     numdofs   = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case XYEnum:   numdofs+=2; break;
+			case XYZPEnum: numdofs+=4; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current solution vector*/
+	values=xNew<IssmDouble>(numdofs);
+	for(i=0;i<numdofs;i++) values[i]=solution[i];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
+
+	/*Transform matrix: R*U */
+	MatrixMultiply(transform,numdofs,numdofs,0,
+				values,numdofs,1,0,
+				&solution[0],0);
+
+	/*Free Matrices*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+void TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum){/*{{{*/
+
+	int* cs_array=NULL;
+
+	/*All nodes have the same Coordinate System*/
+	cs_array=xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
+
+	/*Call core*/
+	TransformStiffnessMatrixCoord(Ke,nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}
+/*}}}*/
+void TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array){/*{{{*/
+
+	int     i,j;
+	int     numdofs   = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case XYEnum:   numdofs+=2; break;
+			case XYZPEnum: numdofs+=4; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current stiffness matrix*/
+	values=xNew<IssmDouble>(Ke->nrows*Ke->ncols);
+	for(i=0;i<Ke->nrows;i++) for(j=0;j<Ke->ncols;j++) values[i*Ke->ncols+j]=Ke->values[i*Ke->ncols+j];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
+
+	/*Transform matrix: R^T*Ke*R */
+	TripleMultiply(transform,numdofs,numdofs,1,
+				values,Ke->nrows,Ke->ncols,0,
+				transform,numdofs,numdofs,0,
+				&Ke->values[0],0);
+
+	/*Free Matrix*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+void CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array){/*{{{*/
+
+	int     i,counter;
+	int     numdofs           = 0;
+	IssmDouble  norm;
+	IssmDouble *transform         = NULL;
+	IssmDouble *values            = NULL;
+	IssmDouble  coord_system[3][3];
+
+	/*Some checks in debugging mode*/
+	_assert_(numnodes && nodes);
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case XYEnum:   numdofs+=2; break;
+			case XYZPEnum: numdofs+=4; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Allocate and initialize transform matrix*/
+	transform=xNew<IssmDouble>(numdofs*numdofs);
+	for(i=0;i<numdofs*numdofs;i++) transform[i]=0.0;
+
+	/*Create transform matrix for all nodes (x,y for 2d and x,y,z for 3d). It is a block matrix
+	 *for 3 nodes:
+
+	 *     | T1 0  0 |
+	 * Q = | 0  T2 0 |
+	 *     | 0  0  T3|
+	 *
+	 * Where T1 is the transform matrix for node 1. It is a simple copy of the coordinate system
+	 * associated to this node*/
+	counter=0;
+	for(i=0;i<numnodes;i++){
+		nodes[i]->GetCoordinateSystem(&coord_system[0][0]);
+		switch(cs_array[i]){
+			case XYEnum:
+				/*We remove the z component, we need to renormalize x and y: x=[x1 x2 0] y=[-x2 x1 0]*/
+				norm = sqrt( coord_system[0][0]*coord_system[0][0] + coord_system[1][0]*coord_system[1][0]); _assert_(norm>1.e-4);
+				transform[(numdofs)*(counter+0) + counter+0] =   coord_system[0][0]/norm;
+				transform[(numdofs)*(counter+0) + counter+1] = - coord_system[1][0]/norm;
+				transform[(numdofs)*(counter+1) + counter+0] =   coord_system[1][0]/norm;
+				transform[(numdofs)*(counter+1) + counter+1] =   coord_system[0][0]/norm;
+				counter+=2;
+				break;
+			case XYZPEnum:
+				/*Only the first 3 coordinates are changed (x,y,z), leave the others (P) unchanged*/
+				transform[(numdofs)*(counter+0) + counter+0] = coord_system[0][0];
+				transform[(numdofs)*(counter+0) + counter+1] = coord_system[0][1];
+				transform[(numdofs)*(counter+0) + counter+2] = coord_system[0][2];
+				transform[(numdofs)*(counter+1) + counter+0] = coord_system[1][0];
+				transform[(numdofs)*(counter+1) + counter+1] = coord_system[1][1];
+				transform[(numdofs)*(counter+1) + counter+2] = coord_system[1][2];
+				transform[(numdofs)*(counter+2) + counter+0] = coord_system[2][0];
+				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;
+				break;
+			default:
+				_error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Assign output pointer*/
+	*ptransform=transform;
+}
+/*}}}*/
+#endif
Index: /issm/trunk/src/c/classes/Node.h
===================================================================
--- /issm/trunk/src/c/classes/Node.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Node.h	(revision 15396)
@@ -0,0 +1,121 @@
+/*!\file Node.h
+ * \brief: header file for node object
+ */
+
+#ifndef _NODE_H_
+#define _NODE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+#include "./DofIndexing.h"
+class  Inputs;
+class  Hook;
+class  IoModel;
+class  DataSet;
+class  Vertices;
+template <class doubletype> class  Vector;
+template <class doubletype> class  Matrix;
+class ElementVector;
+class ElementMatrix;
+#include "Update.h"
+/*}}}*/
+
+class Node: public Object ,public Update{
+
+	private:
+		int approximation; //For ice flow models, we need to know what ice flow approximation is employed on this node
+
+	public: 
+
+		int id;    //unique arbitrary id.
+		int sid;   //"serial" id (rank of this node if the dataset was serial on 1 cpu)
+
+		DofIndexing  indexing;
+		Hook        *hvertex;
+		Inputs      *inputs;               //properties of this node
+		int          analysis_type;
+		IssmDouble   coord_system[3][3];
+
+		/*Node constructors, destructors {{{*/
+		Node();
+		Node(int node_id,int node_sid, int vertex_id,int io_index, IoModel* iomodel,int analysis_type);
+		~Node();
+		/*}}}*/
+		/*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);
+#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);
+		void  DistributeDofs(int* pdofcount,int setenum);
+		void  OffsetDofs(int dofcount,int setenum);
+		void  ShowTrueDofs(int* truerows,int ncols,int setenum);
+		void  UpdateCloneDofs(int* alltruerows,int ncols,int setenum);
+		void  SetClone(int* minranks);
+		/*}}}*/
+};
+
+/*Methods inherent to Node: */
+int* GetLocalDofList(Node** nodes,int numnodes,int setenum,int approximation);
+int* GetGlobalDofList(Node** nodes,int numnodes,int setenum,int approximation);
+int  GetNumberOfDofs(Node** nodes,int numnodes,int setenum,int approximation);
+#ifdef _HAVE_DIAGNOSTIC_
+void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
+void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
+void TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int cs_enum);
+void TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array);
+void TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int cs_enum);
+void TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int* cs_array);
+void TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
+void TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
+void CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array);
+#endif
+
+#endif  /* _NODE_H_ */
Index: /issm/trunk/src/c/classes/Nodes.cpp
===================================================================
--- /issm/trunk/src/c/classes/Nodes.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Nodes.cpp	(revision 15396)
@@ -0,0 +1,355 @@
+/*
+ * \file Nodes.cpp
+ * \brief: Implementation of Nodes class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Nodes.h"
+#include "../shared/shared.h"
+#include "./Node.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Nodes::Nodes(){{{*/
+Nodes::Nodes(){
+	enum_type=NodesEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Nodes::~Nodes(){{{*/
+Nodes::~Nodes(){
+	return;
+}
+/*}}}*/
+
+/*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){
+
+	int  i;
+	int  dofcount=0;
+	int  maxdofspernode=0;
+	int* alldofcount=NULL;
+	int* truedofs=NULL;
+	int* alltruedofs=NULL;
+	int  numnodes=0;
+
+	/*recover my_rank:*/
+	int my_rank   = IssmComm::GetRank();
+	int num_procs = IssmComm::GetSize();
+
+	/*some check: */
+	_assert_(setenum==GsetEnum || setenum==FsetEnum || setenum==SsetEnum);
+
+	/*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)){
+			node->DistributeDofs(&dofcount,setenum);
+		}
+	}
+
+	/* Now every object has distributed dofs, but locally, and with a dof count starting from 
+	 * 0. This means the dofs between all the cpus are not unique. We now offset the dofs of eache
+	 * cpus by the total last dofs of the previus cpu, starting from 0.
+	 * 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
+
+	/* Every cpu should start its own dof count at the end of the dofcount from cpu-1*/
+	dofcount=0;
+	for(i=0;i<my_rank;i++){
+		dofcount+=alldofcount[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));
+		if (node->InAnalysis(analysis_type)){
+			node->OffsetDofs(dofcount,setenum);
+		}
+	}
+
+	/* Finally, remember that cpus may have skipped some objects, because they were clones. For every 
+	 * object that is not a clone, tell them to show their dofs, so that later on, they can get picked 
+	 * up by their clones: */
+	maxdofspernode=this->MaxNumDofs(analysis_type,setenum);
+	numnodes=this->NumberOfNodes(analysis_type);
+	if(numnodes*maxdofspernode){
+		truedofs=   xNewZeroInit<int>(numnodes*maxdofspernode); //initialize to 0, so that we can pick up the max
+		alltruedofs=xNewZeroInit<int>(numnodes*maxdofspernode);
+	}
+
+	for (i=0;i<this->Size();i++){
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		if (node->InAnalysis(analysis_type)){
+			node->ShowTrueDofs(truedofs,maxdofspernode,setenum);//give maxdofspernode, column size, so that nodes can index into truedofs
+		}
+	}
+
+	#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
+
+	/* Now every cpu knows the true dofs of everyone else that is not a clone*/
+	for (i=0;i<this->Size();i++){
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		if (node->InAnalysis(analysis_type)){
+			node->UpdateCloneDofs(alltruedofs,maxdofspernode,setenum);
+		}
+	}
+
+	/* Free ressources: */
+	xDelete<int>(alldofcount);
+	xDelete<int>(truedofs);
+	xDelete<int>(alltruedofs);
+}
+/*}}}*/
+/*FUNCTION Nodes::FlagClones{{{*/
+void  Nodes::FlagClones(int analysis_type){
+
+	int i;
+	int num_procs;
+	int numnodes;
+
+	/*recover num_procs: */
+	num_procs=IssmComm::GetSize();
+
+	/*Figure out number of nodes for this analysis: */
+	numnodes=this->NumberOfNodes(analysis_type);
+
+	/*Allocate ranks: */
+	int* ranks    = xNew<int>(numnodes);
+	int* minranks = xNew<int>(numnodes);
+	for(i=0;i<numnodes;i++)ranks[i]=num_procs; //no cpu can have rank num_procs. This is the maximum limit.
+
+	/*Now go through all our objects and ask them to report to who they belong (which rank): */
+	Ranks(ranks,analysis_type);
+
+	/*We need to take the minimum rank for each vertex, and every cpu needs to get that result. That way, 
+	 * when we start building the dof list for all vertexs, a cpu can check whether its vertex already has been 
+	 * 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
+
+	/*Now go through all objects, and use minranks to flag which objects are cloned: */
+	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 this object, decide whether it is a clone: */
+			node->SetClone(minranks);
+		}
+	}
+
+	/*Free ressources: */
+	xDelete<int>(ranks); 
+	xDelete<int>(minranks);
+
+}
+/*}}}*/
+/*FUNCTION Nodes::MaxNumDofs{{{*/
+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++){
+
+		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)){
+
+			numdofs=node->GetNumberOfDofs(NoneApproximationEnum,setenum);
+			if(numdofs>max)max=numdofs;
+		}
+	}
+
+	/*Grab max of all cpus: */
+	#ifdef _HAVE_MPI_
+	MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
+	max=allmax;
+	#endif
+
+	return max;
+}
+/*}}}*/
+/*FUNCTION Nodes::NumberOfDofs{{{*/
+int   Nodes::NumberOfDofs(int analysis_type,int setenum){
+
+	int   allnumdofs;
+
+	/*Get number of dofs on current cpu (excluding clones)*/
+	int numdofs=this->NumberOfDofsLocal(analysis_type,setenum);
+
+	/*Gather from all cpus: */
+	#ifdef _HAVE_MPI_
+	MPI_Allreduce ( (void*)&numdofs,(void*)&allnumdofs,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
+	#else
+	allnumdofs=numdofs;
+	#endif
+	return allnumdofs;
+}
+/*}}}*/
+/*FUNCTION Nodes::NumberOfDofsLocal{{{*/
+int   Nodes::NumberOfDofsLocal(int analysis_type,int setenum){
+
+	int   numdofs=0;
+
+	/*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)){
+
+			/*Ok, this object is a node, ask it to plug values into partition: */
+			if (!node->IsClone()){
+				numdofs+=node->GetNumberOfDofs(NoneApproximationEnum,setenum);
+			}
+		}
+	}
+
+	return numdofs;
+}
+/*}}}*/
+/*FUNCTION Nodes::NumberOfNodes(){{{*/
+int Nodes::NumberOfNodes(void){
+
+	/*Careful! only use once all clones have been setup for all nodes!: */
+
+	int numnodes=0;
+	int allnumnodes=0;
+
+	/*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));
+
+		/*Ok, this object is a node, ask it to plug values into partition: */
+		if (!node->IsClone()) numnodes++;
+	}
+
+	/*Gather from all cpus: */
+	#ifdef _HAVE_MPI_
+	MPI_Allreduce ( (void*)&numnodes,(void*)&allnumnodes,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
+	#else
+	allnumnodes=numnodes;
+	#endif
+
+	return allnumnodes;
+}
+/*}}}*/
+/*FUNCTION Nodes::NumberOfNodes(analysis){{{*/
+int Nodes::NumberOfNodes(int analysis_type){
+
+	int i;
+
+	int max_sid=-1;
+	int sid;
+	int node_max_sid;
+
+	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)){
+
+			sid=node->Sid();
+			if (sid>max_sid)max_sid=sid;
+		}
+	}
+
+	#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());
+	max_sid=node_max_sid;
+	#endif
+
+	/*sid starts at 0*/
+	max_sid++;
+
+	/*return*/
+	return max_sid;
+}
+/*}}}*/
+/*FUNCTION Nodes::Ranks{{{*/
+void   Nodes::Ranks(int* ranks,int analysis_type){
+
+	int my_rank;
+	int sid;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*Go through nodes, and for each object, report it cpu: */
+	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)){
+			/*Plug rank into ranks, according to sid: */
+			sid=node->Sid();
+			ranks[sid]=my_rank; 
+		}
+	}
+}
+/*}}}*/
+/*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);
+
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Nodes.h
===================================================================
--- /issm/trunk/src/c/classes/Nodes.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Nodes.h	(revision 15396)
@@ -0,0 +1,40 @@
+#ifndef _CONTAINER_NODES_H_
+#define  _CONTAINER_NODES_H_
+
+#include "../datastructures/datastructures.h"
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+class Materials;
+
+/*!\brief Declaration of Nodes class.
+ *
+ * Declaration of Nodes class.  Nodes are vector lists of objects (Containers) of Node objects.
+ * Node objects are the degrees of freedom (DOFs) for a particular analysis type (not to be 
+ * confused with a vertex, which defines the (x,y,z) location of a point).
+ */ 
+class Nodes: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Nodes();
+		~Nodes();
+
+		/*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);
+		int   MaxNumDofs(int analysis_type,int setenum);
+		int   NumberOfDofs(int analysis_type,int setenum);
+		int   NumberOfDofsLocal(int analysis_type,int setenum);
+		int   NumberOfNodes(int analysis_type);
+		int   NumberOfNodes(void);
+		void  Ranks(int* ranks,int analysis_type);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+
+};
+
+#endif //ifndef _NODES_H_
Index: sm/trunk/src/c/classes/OptArgs.h
===================================================================
--- /issm/trunk/src/c/classes/OptArgs.h	(revision 15395)
+++ 	(revision )
@@ -1,13 +1,0 @@
-/*!\file:  OptArgs.h
- * \brief place holder for optimization function arguments
- */ 
-
-#ifndef _OPTARGS_H_
-#define _OPTARGS_H_
-
-class Model;
-struct OptArgs{
-	FemModel* femmodel;
-};
-
-#endif
Index: sm/trunk/src/c/classes/OptPars.h
===================================================================
--- /issm/trunk/src/c/classes/OptPars.h	(revision 15395)
+++ 	(revision )
@@ -1,17 +1,0 @@
-/*!\file:  OptPars.h
- * \brief place holder for optimization parameters
- */ 
-
-#ifndef _OPTPARS_H_
-#define _OPTPARS_H_
-
-struct OptPars{
-
-	IssmDouble xmin;
-	IssmDouble xmax;
-	IssmDouble cm_jump;
-	int maxiter;
-
-};
-
-#endif
Index: /issm/trunk/src/c/classes/Options/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Options/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/classes/Options/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,8 @@
+# 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: /issm/trunk/src/c/classes/Options/GenericOption.h
===================================================================
--- /issm/trunk/src/c/classes/Options/GenericOption.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Options/GenericOption.h	(revision 15396)
@@ -0,0 +1,134 @@
+/*! \file GenericOption.h 
+ *  \brief: header file for generic option object
+ */
+
+#ifndef _GENERIC_OPTION_
+#define _GENERIC_OPTION_
+
+/*Headers:{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+#include "../../shared/shared.h"
+#include "../../datastructures/datastructures.h"
+#include "./OptionUtilities.h"
+/*}}}*/
+
+template <class OptionType> 
+class GenericOption: public Option {
+
+	public:
+
+		char       *name;
+		OptionType  value;
+
+		int         numel;   //in case OptionType is an array
+		int         ndims;   //in case OptionType is a multi-dimensional array: */
+		int        *size;
+
+		/*GenericOption constructors, destructors*/
+		GenericOption(){ /*{{{*/
+
+			name   = NULL;
+			numel  = 0;
+			ndims  = 0;
+			size   = NULL;
+
+		} /*}}}*/
+		~GenericOption(){ /*{{{*/
+
+			if(name)   xDelete<char>(name);
+			if(size)   xDelete<int>(size);
+
+		} /*}}}*/
+
+		/*Object virtual functions definitions:*/
+		void Echo(){ /*{{{*/
+
+			this->DeepEcho();
+
+		} /*}}}*/
+		void DeepEcho(){ /*{{{*/
+
+			char  indent[81]="";
+			this->DeepEcho(indent);
+
+		} /*}}}*/
+		void DeepEcho(char* indent){ /*{{{*/
+
+			char  cstr[81];
+			bool  flag=true;
+
+			if(flag) _printf0_(indent << "         name: \"" << name << "\"\n");
+			if(flag) _printf0_(indent << "         numel: " << numel << "\n");
+			if(flag) _printf0_(indent << "         ndims: " << ndims << "\n");
+			if(size){
+				StringFromSize(cstr,size,ndims);
+				if(flag) _printf0_(indent << "          size: " << cstr << "\n");
+			}
+			else if(flag) _printf0_(indent << "          size: [empty]\n");
+			_printf_(indent << "         value: " << value << "\n");;
+		} /*}}}*/
+		int  Id(){/*{{{*/
+			_error_("Not implemented yet");
+		};/*}}}*/
+		int  ObjectEnum(){/*{{{*/
+			return GenericOptionEnum;
+		};/*}}}*/
+		Object* copy(){/*{{{*/
+			_error_("Not implemented yet");
+		};/*}}}*/
+
+		/*GenericOption functions: */
+		char* Name(){/*{{{*/
+			return name;
+		};/*}}}*/
+		int   NumEl(){/*{{{*/
+			return numel;
+		};/*}}}*/
+		int   NDims(){/*{{{*/
+			return ndims;
+		};/*}}}*/
+		int*  Size(){/*{{{*/
+			return size;
+		};/*}}}*/
+		void  Get(OptionType* pvalue){/*{{{*/
+			*pvalue=value; 
+		};/*}}}*/
+};
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)  //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization. 
+template <> inline void GenericOption<IssmPDouble*>::Get(IssmPDouble** pvalue){ /*{{{*/
+
+	/*Copy vector*/
+	IssmPDouble* outvalue=xNew<IssmPDouble>(this->NumEl());
+	for(int i=0;i<this->NumEl();i++) outvalue[i]=this->value[i];
+
+	/*Assign output pointer*/
+	*pvalue=outvalue;
+} /*}}}*/
+#endif
+template <> inline void GenericOption<IssmDouble*>::Get(IssmDouble** pvalue){ /*{{{*/
+
+	/*Copy vector*/
+	IssmDouble* outvalue=xNew<IssmDouble>(this->NumEl());
+	for(int i=0;i<this->NumEl();i++) outvalue[i]=this->value[i];
+
+	/*Assign output pointer*/
+	*pvalue=outvalue;
+} /*}}}*/
+template <> inline void GenericOption<char*>::Get(char** pvalue){ /*{{{*/
+
+	int   stringsize=strlen(this->value)+1;
+	char* outstring=xNew<char>(stringsize);
+	xMemCpy<char>(outstring,this->value,stringsize);
+
+	*pvalue=outstring;
+} 
+/*}}}*/
+
+#endif  /* _OPTIONOBJECT_H */
Index: /issm/trunk/src/c/classes/Options/Option.h
===================================================================
--- /issm/trunk/src/c/classes/Options/Option.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Options/Option.h	(revision 15396)
@@ -0,0 +1,36 @@
+/*! \file Option.h 
+ *  \brief: header file for option abstract object
+ */
+
+#ifndef _OPTIONOBJECT_H_
+#define _OPTIONOBJECT_H_
+
+/*Headers:{{{*/
+#include "../../shared/shared.h"
+#include "../../datastructures/datastructures.h"
+/*}}}*/
+
+class Option: public Object {
+
+	public:
+
+		/*Option constructors, destructors*/
+		Option(){};
+		~Option(){};
+
+		/*Object virtual functions definitions*/
+		virtual void  Echo()= 0;
+		virtual void  DeepEcho()= 0;
+		virtual void  DeepEcho(char  *indent)=0;
+		int           Id(){_error_("Not implemented yet"); };
+		int           ObjectEnum(){return OptionEnum;              };
+		Object       *copy(){_error_("Not implemented yet"); };
+
+		/*virtual functions: */
+		virtual char* Name()=0;
+		virtual int   NumEl()=0;
+		virtual int   NDims()=0;
+		virtual int*  Size()=0;
+
+};
+#endif  /* _OPTIONOBJECT_H */
Index: /issm/trunk/src/c/classes/Options/OptionUtilities.cpp
===================================================================
--- /issm/trunk/src/c/classes/Options/OptionUtilities.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Options/OptionUtilities.cpp	(revision 15396)
@@ -0,0 +1,110 @@
+/*!\file OptionUtilities.cpp
+ * \brief: implementation of the options utilities
+ */
+
+/*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"
+/*}}}*/
+
+/*FUNCTION ColumnWiseDimsFromIndex{{{*/
+int ColumnWiseDimsFromIndex(int* dims,int index,int* size,int ndims){
+
+	int   i;
+	int   aprod=1;
+
+	/*check for index too large  */
+	for (i=0;i<ndims;i++) aprod*=size[i];
+	if (index >= aprod) _error_("Index " << index << " exceeds number of elements " << aprod << ".");
+
+	/*calculate the dimensions (being careful of integer division)  */
+	for (i=ndims-1; i>=0; i--) {
+		aprod=reCast<int>(((IssmPDouble)aprod+0.5)/(IssmPDouble)size[i]);
+		dims[i]=(int)floor(((IssmPDouble)index+0.5)/(IssmPDouble)aprod);
+		index-=dims[i]*aprod;
+	}
+
+	return(0);
+}/*}}}*/
+/*FUNCTION IndexFromColumnWiseDims{{{*/
+int IndexFromColumnWiseDims(int* dims, int* size, int ndims) {
+
+	int   i;
+	int   index=0;
+
+	/*check for any dimension too large  */
+	for (i=0;i<ndims;i++){
+		if (dims[i] >= size[i]) _error_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
+	}
+
+	/*calculate the index  */
+	for (i=ndims-1; i>=0; i--){
+		index*=size[i];
+		index+=dims[i];
+	}
+
+	return(index);
+}/*}}}*/
+/*FUNCTION RowWiseDimsFromIndex{{{*/
+int RowWiseDimsFromIndex(int* dims, int index, int* size, int ndims) {
+
+	int   i;
+	int   aprod=1;
+
+	/*check for index too large  */
+	for (i=0; i<ndims; i++) aprod*=size[i];
+	if (index >= aprod) _error_("Index " << index << " exceeds number of elements " << aprod << ".");
+
+	/*calculate the dimensions (being careful of integer division)  */
+	for (i=0; i<ndims; i++) {
+		aprod=(int)(((IssmPDouble)aprod+0.5)/(IssmPDouble)size[i]);
+		dims[i]=(int)floor(((IssmPDouble)index+0.5)/(IssmPDouble)aprod);
+		index-=dims[i]*aprod;
+	}
+
+	return(0);
+}/*}}}*/
+/*FUNCTION IndexFromRowWiseDims{{{*/
+int IndexFromRowWiseDims(int* dims, int* size, int ndims) {
+
+	int   i;
+	int   index=0;
+
+	/*check for any dimension too large  */
+	for (i=0; i<ndims; i++){
+		if (dims[i] >= size[i]) _error_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
+	}
+
+	/*calculate the index  */
+	for (i=0; i<ndims; i++) {
+		index*=size[i];
+		index+=dims[i];
+	}
+
+	return(index);
+}/*}}}*/
+/*FUNCTION StringFromDims{{{*/
+int StringFromDims(char* cstr, int* dims, int ndims) {
+
+	sprintf(&cstr[0],"[");
+	for(int i=0; i<ndims-1; i++) sprintf(&cstr[strlen(cstr)],"%d,",dims[i]);
+	sprintf(&cstr[strlen(cstr)],"%d]",dims[ndims-1]);
+
+	return(0);
+}/*}}}*/
+/*FUNCTION StringFromSize{{{*/
+int StringFromSize(char* cstr, int* size, int ndims) {
+
+	sprintf(&cstr[0],"[");
+	for(int i=0; i<ndims-1; i++) sprintf(&cstr[strlen(cstr)],"%dx",size[i]);
+	sprintf(&cstr[strlen(cstr)],"%d]",size[ndims-1]);
+
+	return(0);
+}/*}}}*/
Index: /issm/trunk/src/c/classes/Options/OptionUtilities.h
===================================================================
--- /issm/trunk/src/c/classes/Options/OptionUtilities.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Options/OptionUtilities.h	(revision 15396)
@@ -0,0 +1,22 @@
+/*! \file OptionUtilities.h 
+ *  \brief: header file for option object utilities
+ */
+
+#ifndef _OPTIONUTILITIES_H_
+#define _OPTIONUTILITIES_H_
+
+/*Headers:{{{*/
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/Enum/Enum.h"
+
+#include "./Option.h"
+/*}}}*/
+
+int ColumnWiseDimsFromIndex(int* dims, int index, int* size, int ndims);
+int IndexFromColumnWiseDims(int* dims, int* size, int ndims);
+int RowWiseDimsFromIndex(int* dims, int index, int* size, int ndims);
+int IndexFromRowWiseDims(int* dims, int* size, int ndims);
+int StringFromDims(char* cstr, int* dims, int ndims);
+int StringFromSize(char* cstr, int* size, int ndims);
+
+#endif  /* _OPTIONUTILITIES_H */
Index: /issm/trunk/src/c/classes/Options/Options.cpp
===================================================================
--- /issm/trunk/src/c/classes/Options/Options.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Options/Options.cpp	(revision 15396)
@@ -0,0 +1,111 @@
+/*
+ * \file Options.cpp
+ * \brief: Implementation of Options class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <vector>
+#include <algorithm>
+#include <cstring>
+
+#include "./Options.h"
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Options::Options(){{{*/
+Options::Options(){
+	return;
+}
+/*}}}*/
+/*FUNCTION Options::~Options(){{{*/
+Options::~Options(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Options::AddOption{{{*/
+int  Options::AddOption(Option* in_option){
+
+	char* name=NULL;
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*In debugging mode, check that the option is not a NULL pointer*/
+	_assert_(in_option);
+
+	/*Also, check the option name*/
+	name=in_option->Name();
+
+	if(!name) _error_("input option has an empty name");
+	if(strchr(name,'.')) _error_("Option \"" << name << "\" has a protected character \".\"");
+	if(strchr(name,'[')) _error_("Option \"" << name << "\" has a protected character \"[\"");
+	if(strchr(name,']')) _error_("Option \"" << name << "\" has a protected character \"]\"");
+
+	/*Finally, check that no option of the same name already exists in the dataset*/
+	for(object=objects.begin();object<objects.end();object++){
+
+		option=dynamic_cast<Option*>(*object);
+		if (!strcmp(option->Name(),name)){
+			_error_("Options \"" << name << "\" found multiple times");
+			break;
+		}
+	}
+
+	/*OK, all checks went well, add option to dataset*/
+	this->AddObject(in_option);
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Options::GetOption{{{*/
+Option* Options::GetOption(const char* name){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*Go through options and find option: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		option=dynamic_cast<Option*>(*object);
+		if (!strncmp(name,option->Name(),strlen(option->Name()))){
+
+			/*OK, now do we have a complete name? If not, it is a cell or a structure, we need to go further*/
+			if(!strcmp(name,option->Name())){
+				return option;
+			}
+			else{
+				/*If the object is a Cell, recursive call to its options*/ 
+				if(option->ObjectEnum()==OptionCellEnum){
+					GenericOption<Options*>* celloption=(GenericOption<Options*>*)option;
+					return celloption->value->GetOption(name);
+				}
+				/*If the object is a Struct loop over its size and recursive call*/
+				else if(option->ObjectEnum()==OptionStructEnum){
+					for(int i=0;i<option->NumEl();i++){
+						GenericOption<Options**>* structoption=(GenericOption<Options**>*)option;
+						_assert_(structoption->value[i]);
+						return structoption->value[i]->GetOption(name);
+					}
+				}
+				/*Else: not supported*/
+				else{
+					_error_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
+				}
+			}
+		}
+	}
+
+	/*Option not found return NULL pointer*/
+	return NULL;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Options/Options.h
===================================================================
--- /issm/trunk/src/c/classes/Options/Options.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Options/Options.h	(revision 15396)
@@ -0,0 +1,108 @@
+#ifndef _CONTAINER_OPTIONS_H_
+#define _CONTAINER_OPTIONS_H_
+
+/*forward declarations */
+class Option;
+#include "../../datastructures/datastructures.h"
+#include "./GenericOption.h"
+
+/*!\brief Declaration of Options class. 
+ * 
+ * Declaration of Options class.  Options are vector lists (Containers) of Option objects.
+ */ 
+class Options: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Options();
+		~Options();
+
+		/*numerics*/
+		int  AddOption(Option* in_oobject);
+		Option* GetOption(const char* name);
+
+		template <class OptionType> void Get(OptionType* pvalue,const char* name){ /*{{{*/
+
+			/*Get option*/
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+			}
+			/*Else, the Option does not exist, no default provided*/
+			else{
+				_error_("option of name \"" << name << "\" not found, and no default value has been provided");
+			}
+		}
+		/*}}}*/
+		template <class OptionType> void Get(OptionType* pvalue,int* pnumel, const char* name){ /*{{{*/
+
+			/*Get option*/
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+				*pnumel=genericoption->NumEl();
+			}
+			/*Else, the Option does not exist, no default provided*/
+			else{
+				_error_("option of name \"" << name << "\" not found, and no default value has been provided");
+			}
+		}
+		/*}}}*/
+		template <class OptionType> void Get(OptionType* pvalue,const char* name,OptionType default_value){ /*{{{*/
+
+			/*Get option*/
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+			}
+			else{
+				if(GetOption(name)) _printf_("WARNING: option "<<name<<" found but fetched format not consistent, defaulting...\n");
+				*pvalue=default_value;
+			}
+		}
+		/*}}}*/
+		template <class OptionType> void Get(OptionType* pvalue,int* pnumel, const char* name,OptionType default_value){ /*{{{*/
+
+			/*Get option*/
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+				*pnumel=genericoption->NumEl();
+			}
+			else{
+				*pvalue=default_value;
+			}
+		}
+		/*}}}*/
+
+};
+
+#endif //ifndef _INPUTS_H_
+
+template <> inline void Options::Get(char** pvalue,const char* name,char* default_value){ /*{{{*/
+
+	/*Get option*/
+	GenericOption<char*>* genericoption=dynamic_cast<GenericOption<char*>*>(GetOption(name));
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(genericoption){
+		genericoption->Get(pvalue);
+	}
+	else{
+		/*Make a copy*/
+		int   stringsize=strlen(default_value)+1;
+		char* outstring=xNew<char>(stringsize);
+		xMemCpy<char>(outstring,default_value,stringsize);
+		*pvalue=outstring;
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/BoolParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/BoolParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/BoolParam.cpp	(revision 15396)
@@ -0,0 +1,73 @@
+/*!\file BoolParam.c
+ * \brief: implementation of the BoolParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*BoolParam constructors and destructor*/
+/*FUNCTION BoolParam::BoolParam(){{{*/
+BoolParam::BoolParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolParam::BoolParam(int enum_type,bool value){{{*/
+BoolParam::BoolParam(int in_enum_type,bool in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION BoolParam::~BoolParam(){{{*/
+BoolParam::~BoolParam(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION BoolParam::Echo {{{*/
+void BoolParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION BoolParam::DeepEcho{{{*/
+void BoolParam::DeepEcho(void){
+
+	_printf_("BoolParam:\n");
+	_printf_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   value: " <<(this->value?"true":"false") << "\n");
+}
+/*}}}*/
+/*FUNCTION BoolParam::Id{{{*/
+int    BoolParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolParam::ObjectEnum{{{*/
+int BoolParam::ObjectEnum(void){
+
+	return BoolParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION BoolParam::copy{{{*/
+Object* BoolParam::copy() {
+
+	return new BoolParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*BoolParam virtual functions definitions: */
+/*FUNCTION BoolParam::GetParameterName{{{*/
+void BoolParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/BoolParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/BoolParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/BoolParam.h	(revision 15396)
@@ -0,0 +1,74 @@
+/*! \file BoolParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _BOOLPARAM_H_
+#define _BOOLPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class BoolParam: public Param{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		bool value;
+
+		/*BoolParam constructors, destructors: {{{*/
+		BoolParam();
+		BoolParam(int enum_type,bool value);
+		~BoolParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){*pbool=value;}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){this->value=boolean;}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an IssmPDouble");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif  /* _BOOLPARAM_H */
Index: /issm/trunk/src/c/classes/Params/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Params/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,23 @@
+# 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/Params/DataSetParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DataSetParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DataSetParam.cpp	(revision 15396)
@@ -0,0 +1,79 @@
+/*!\file DataSetParam.c
+ * \brief: implementation of the DataSetParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*DataSetParam constructors and destructor*/
+/*FUNCTION DataSetParam::DataSetParam(){{{*/
+DataSetParam::DataSetParam(){
+	value=NULL;
+	return;
+}
+/*}}}*/
+/*FUNCTION DataSetParam::DataSetParam(int enum_type,DataSet *value){{{*/
+DataSetParam::DataSetParam(int in_enum_type,DataSet* in_value){
+
+	enum_type=in_enum_type;
+	value=in_value->Copy();;
+}
+/*}}}*/
+/*FUNCTION DataSetParam::~DataSetParam(){{{*/
+DataSetParam::~DataSetParam(){
+	delete value;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DataSetParam::Echo {{{*/
+void DataSetParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DataSetParam::DeepEcho{{{*/
+void DataSetParam::DeepEcho(void){
+
+	_printf_("DataSetParam:\n");
+	_printf_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	this->value->Echo();
+}
+/*}}}*/
+/*FUNCTION DataSetParam::Id{{{*/
+int    DataSetParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DataSetParam::ObjectEnum{{{*/
+int DataSetParam::ObjectEnum(void){
+
+	return DataSetParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION DataSetParam::copy{{{*/
+Object* DataSetParam::copy() {
+
+	return new DataSetParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*DataSetParam virtual functions definitions: */
+/*FUNCTION DataSetParam::GetParameterName{{{*/
+void DataSetParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DataSetParam::GetParameterValue{{{*/
+void DataSetParam::GetParameterValue(DataSet** pdataset){
+	*pdataset=value->Copy();
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/DataSetParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DataSetParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DataSetParam.h	(revision 15396)
@@ -0,0 +1,76 @@
+/*! \file DataSetParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DATASETPARAM_H_
+#define _DATASETPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DataSetParam: public Param{
+
+	private: 
+		int   enum_type;
+		DataSet* value;
+
+	public:
+		/*DataSetParam constructors, destructors: {{{*/
+		DataSetParam();
+		DataSetParam(int enum_type,DataSet* dataset);
+		~DataSetParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){  _error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(FILE** pfile){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a file pointer");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("DataSet param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(DataSet** pdataset);
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a file pointer");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(DataSet* dataset){_error_("DataSet param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a DataSet yet");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("DataSet param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.cpp	(revision 15396)
@@ -0,0 +1,227 @@
+/*!\file DoubleMatArrayParam.c
+ * \brief: implementation of the DoubleMatArrayParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*DoubleMatArrayParam constructors and destructor*/
+/*FUNCTION DoubleMatArrayParam::DoubleMatArrayParam(){{{*/
+DoubleMatArrayParam::DoubleMatArrayParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::DoubleMatArrayParam(int enum_type,IssmDouble** array, int M, int* mdim_array, int* ndim_array){{{*/
+DoubleMatArrayParam::DoubleMatArrayParam(int in_enum_type,IssmDouble** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){
+
+	int i;
+	IssmDouble* matrix=NULL;
+	int     m,n;
+
+	enum_type=in_enum_type;
+	M=in_M;
+	if(M){
+		array=xNew<IssmDouble*>(M);
+		mdim_array=xNew<int>(M);
+		ndim_array=xNew<int>(M);
+
+		for(i=0;i<M;i++){
+			m=in_mdim_array[i]; 
+			n=in_ndim_array[i];
+
+			mdim_array[i]=m;
+			ndim_array[i]=n;
+
+			if(m*n){
+				matrix=xNew<IssmDouble>(m*n);
+				xMemCpy<IssmDouble>(matrix,in_array[i],m*n);
+			}
+			else{
+				matrix=NULL;
+			}
+			array[i]=matrix;
+		}
+	}
+	else{
+		array=NULL;
+		mdim_array=NULL;
+		ndim_array=NULL;
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::~DoubleMatArrayParam(){{{*/
+DoubleMatArrayParam::~DoubleMatArrayParam(){
+
+	int i;
+	IssmDouble* matrix=NULL;
+
+	xDelete<int>(mdim_array);
+	xDelete<int>(ndim_array);
+
+	for(i=0;i<M;i++){
+		matrix=array[i];
+		xDelete<IssmDouble>(matrix);
+	}
+
+	xDelete<IssmDouble*>(array);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleMatArrayParam::Echo {{{*/
+void DoubleMatArrayParam::Echo(void){
+
+	_printf_("DoubleMatArrayParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   array size: " << this->M << "\n");
+	_printf_("   array pointer: " << this->array << "\n");
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::DeepEcho{{{*/
+void DoubleMatArrayParam::DeepEcho(void){
+
+	int i,j,k;
+	int m,n;
+	IssmDouble* matrix=NULL;
+
+	_printf_("DoubleMatArrayParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   array size: " << this->M << "\n");
+	for(i=0;i<M;i++){
+		_printf_("   array " << i << " (" << mdim_array[i] << "x" << ndim_array[i] << "):\n");
+		matrix=array[i];
+		m=mdim_array[i];
+		n=ndim_array[i];
+
+		for(j=0;j<m;j++){
+			_printf_("   ");
+			for(k=0;k<n;k++)_printf_(*(matrix+n*j+k) << " ");
+			_printf_("\n");
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::Id{{{*/
+int    DoubleMatArrayParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::ObjectEnum{{{*/
+int DoubleMatArrayParam::ObjectEnum(void){
+
+	return DoubleMatArrayParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::copy{{{*/
+Object* DoubleMatArrayParam::copy() {
+
+	return new DoubleMatArrayParam(this->enum_type,this->array, this->M, this->mdim_array,this->ndim_array);
+
+}
+/*}}}*/
+
+/*DoubleMatArrayParam virtual functions definitions: */
+/*FUNCTION DoubleMatArrayParam::GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){{{*/
+void  DoubleMatArrayParam::GetParameterValue(IssmDouble*** pout_array, int* pout_M,int** pout_mdim_array, int** pout_ndim_array){
+
+	int i,m,n;
+	IssmDouble* matrix=NULL;
+	IssmDouble* out_matrix=NULL;
+
+	/*output: */
+	IssmDouble** out_array=NULL;
+	int      out_M;
+	int*     out_mdim_array=NULL;
+	int*     out_ndim_array=NULL;
+
+	out_M=this->M;
+	if(out_M){
+		out_array=xNew<IssmDouble*>(M);
+		out_mdim_array=xNew<int>(M);
+		out_ndim_array=xNew<int>(M);
+
+		xMemCpy<int>(out_mdim_array,this->mdim_array,M);
+		xMemCpy<int>(out_ndim_array,this->ndim_array,M);
+
+		for(i=0;i<this->M;i++){
+			matrix=this->array[i];
+			m=this->mdim_array[i];
+			n=this->ndim_array[i];
+
+			if(m*n){
+				out_matrix=xNew<IssmDouble>(m*n);
+				xMemCpy<IssmDouble>(out_matrix,matrix,m*n);
+			}
+			else{
+				out_matrix=NULL;
+			}
+			out_array[i]=out_matrix;
+		}
+	}
+	else{
+		out_array=NULL;
+		out_matrix=NULL;
+		out_ndim_array=NULL;
+	}
+
+	/*Assign output pointers:*/
+	if(pout_M) *pout_M=out_M;
+	if(pout_mdim_array) *pout_mdim_array=out_mdim_array;
+	if(pout_ndim_array) *pout_ndim_array=out_ndim_array;
+	*pout_array=out_array;
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::GetParameterName{{{*/
+void DoubleMatArrayParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){{{*/
+void  DoubleMatArrayParam::SetValue(IssmDouble** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){
+
+	int i,m,n;
+	IssmDouble* in_matrix=NULL;
+	IssmDouble* matrix=NULL;
+
+	/*avoid leak: */
+	xDelete<int>(mdim_array);
+	xDelete<int>(ndim_array);
+	for(i=0;i<M;i++){
+		matrix=array[i];
+		xDelete<IssmDouble>(matrix);
+	}
+	xDelete<IssmDouble*>(array);
+
+	/*copy data: */
+	this->M=in_M;
+	this->array=xNew<IssmDouble*>(M);
+	this->mdim_array=xNew<int>(M);
+	this->ndim_array=xNew<int>(M);
+
+	xMemCpy<int>(this->mdim_array,in_mdim_array,M);
+	xMemCpy<int>(this->ndim_array,in_ndim_array,M);
+
+	for(i=0;i<M;i++){
+		in_matrix=in_array[i];
+		m=in_mdim_array[i];
+		n=in_ndim_array[i];
+
+		matrix=xNew<IssmDouble>(m*n);
+		xMemCpy<IssmDouble>(matrix,in_matrix,m*n);
+
+		this->array[i]=matrix;
+	}
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DoubleMatArrayParam.h	(revision 15396)
@@ -0,0 +1,78 @@
+/*! \file DoubleMatArrayParam.h 
+ *  \brief: header file for object holding an array of serial matrices
+ */
+
+#ifndef _DOUBLEMATARRAYPARAM_H_
+#define _DOUBLEMATARRAYPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleMatArrayParam: public Param{
+
+	private: 
+		int          enum_type;
+		IssmDouble **array;        //array of matrices
+		int          M;            //size of array
+		int         *mdim_array;   //m-dimensions of matrices in the array
+		int         *ndim_array;   //n-dimensions -f matrices in the array
+
+	public:
+		/*DoubleMatArrayParam constructors, destructors: {{{*/
+		DoubleMatArrayParam();
+		DoubleMatArrayParam(int enum_type,IssmDouble** array, int M, int* mdim_array, int* ndim_array);
+		~DoubleMatArrayParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims);
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a int mat array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATARRAYPARAM_H */
Index: /issm/trunk/src/c/classes/Params/DoubleMatParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleMatParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DoubleMatParam.cpp	(revision 15396)
@@ -0,0 +1,120 @@
+/*!\file DoubleMatParam.c
+ * \brief: implementation of the DoubleMatParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*DoubleMatParam constructors and destructor*/
+/*FUNCTION DoubleMatParam::DoubleMatParam(){{{*/
+DoubleMatParam::DoubleMatParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::DoubleMatParam(int enum_type,IssmDoubleMat value){{{*/
+DoubleMatParam::DoubleMatParam(int in_enum_type,IssmDouble* in_value, int in_M,int in_N){
+
+	enum_type=in_enum_type;
+	M=in_M;
+	N=in_N;
+
+	value=xNew<IssmDouble>(M*N);
+	xMemCpy<IssmDouble>(value,in_value,M*N);
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::~DoubleMatParam(){{{*/
+DoubleMatParam::~DoubleMatParam(){
+	xDelete<IssmDouble>(value);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleMatParam::Echo {{{*/
+void DoubleMatParam::Echo(void){
+
+	_printf_("DoubleMatParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   matrix size: " << this->M << "x" << this->N << "\n");
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::DeepEcho{{{*/
+void DoubleMatParam::DeepEcho(void){
+
+	int i,j;
+
+	_printf_("DoubleMatParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   matrix size: " << this->M << "x" << this->N << "\n");
+	for(i=0;i<this->M;i++){
+		for(i=0;i<this->N;i++){
+			_printf_(i << " " << j << " " << *(this->value+N*i+j) << "\n");
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::Id{{{*/
+int    DoubleMatParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleMatParam::ObjectEnum{{{*/
+int DoubleMatParam::ObjectEnum(void){
+
+	return DoubleMatParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::copy{{{*/
+Object* DoubleMatParam::copy() {
+
+	return new DoubleMatParam(this->enum_type,this->value,this->M,this->N);
+
+}
+/*}}}*/
+
+/*DoubleMatParam virtual functions definitions: */
+/*FUNCTION DoubleMatParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){{{*/
+void  DoubleMatParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){
+	IssmDouble* output=NULL;
+
+	output=xNew<IssmDouble>(M*N);
+	xMemCpy<IssmDouble>(output,value,M*N);
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	if(pN) *pN=N;
+	*pIssmDoublearray=output;
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){{{*/
+void  DoubleMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){
+	_error_("DoubleMat of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::GetParameterName{{{*/
+void DoubleMatParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::SetValue{{{*/
+void  DoubleMatParam::SetValue(IssmDouble* IssmDoublearray,int in_M,int in_N){
+
+	/*avoid leak: */
+	xDelete<IssmDouble>(this->value);
+
+	this->value=xNew<IssmDouble>(in_M*in_N);
+	xMemCpy<IssmDouble>(this->value,IssmDoublearray,in_M*in_N);
+
+	this->M=in_M;
+	this->N=in_N;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/DoubleMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleMatParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DoubleMatParam.h	(revision 15396)
@@ -0,0 +1,77 @@
+/*! \file DoubleMatParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DOUBLEMATPARAM_H_
+#define _DOUBLEMATPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleMatParam: public Param{
+
+	protected: 
+		int         enum_type;
+		IssmDouble *value;
+		int         M;
+		int         N;
+
+	public:
+		/*DoubleMatParam constructors, destructors: {{{*/
+		DoubleMatParam();
+		DoubleMatParam(int enum_type,IssmDouble* value,int M,int N);
+		~DoubleMatParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N);
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATPARAM_H */
Index: /issm/trunk/src/c/classes/Params/DoubleParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DoubleParam.cpp	(revision 15396)
@@ -0,0 +1,100 @@
+/*!\file DoubleParam.c
+ * \brief: implementation of the DoubleParam 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"
+
+/*DoubleParam constructors and destructor*/
+/*FUNCTION DoubleParam::DoubleParam(){{{*/
+DoubleParam::DoubleParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleParam::DoubleParam(int enum_type,IssmDouble value){{{*/
+DoubleParam::DoubleParam(int in_enum_type,IssmDouble in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION DoubleParam::~DoubleParam(){{{*/
+DoubleParam::~DoubleParam(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleParam::Echo {{{*/
+void DoubleParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DoubleParam::DeepEcho{{{*/
+void DoubleParam::DeepEcho(void){
+
+	_printf_("DoubleParam:\n");
+	_printf_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   value: " << this->value << "\n");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::Id{{{*/
+int    DoubleParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleParam::ObjectEnum{{{*/
+int DoubleParam::ObjectEnum(void){
+
+	return DoubleParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleParam::copy{{{*/
+Object* DoubleParam::copy() {
+
+	return new DoubleParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*DoubleParam virtual functions definitions: */
+/*FUNCTION DoubleParam::GetParameterName{{{*/
+void DoubleParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(int* pinteger){{{*/
+void DoubleParam::GetParameterValue(int* pinteger){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(bool* pbool){{{*/
+void DoubleParam::GetParameterValue(bool* pbool){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an bool");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(int** pintarray,int* pM){{{*/
+void DoubleParam::GetParameterValue(int** pintarray,int* pM){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){{{*/
+void DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){{{*/
+void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){{{*/
+void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/DoubleParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DoubleParam.h	(revision 15396)
@@ -0,0 +1,76 @@
+/*! \file DoubleParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DOUBLEPARAM_H_
+#define _DOUBLEPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int        enum_type;
+		IssmDouble value;
+
+	public:
+		/*DoubleParam constructors, destructors: {{{*/
+		DoubleParam();
+		DoubleParam(int enum_type,IssmDouble value);
+		~DoubleParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool);
+		void  GetParameterValue(int* pinteger);
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble* pIssmDouble){*pIssmDouble=value;}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM);
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN);
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){this->value=(IssmDouble)boolean;}
+		void  SetValue(int integer){this->value=(IssmDouble)integer;}
+		void  SetValue(IssmDouble scalar){this->value=(IssmDouble)scalar;}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEPARAM_H */
Index: /issm/trunk/src/c/classes/Params/DoubleTransientMatParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleTransientMatParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DoubleTransientMatParam.cpp	(revision 15396)
@@ -0,0 +1,20 @@
+/*!\file DoubleTransientMatParam.c
+ * \brief: implementation of the DoubleTransientMatParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*FUNCTION DoubleTransientMatParam::DoubleTransientMatParam(int enum_type,IssmDoubleMat value){{{*/
+DoubleTransientMatParam::DoubleTransientMatParam(int in_enum_type,IssmDouble* in_value, int in_M,int in_N):DoubleMatParam(in_enum_type,in_value,in_M,in_N){
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/DoubleTransientMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleTransientMatParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DoubleTransientMatParam.h	(revision 15396)
@@ -0,0 +1,27 @@
+/*! \file DoubleTransientMatParam.h 
+ *  \brief: header file for DoubleTransientMatParam object
+ */
+
+#ifndef _DOUBLETRANSIENTMATPARAM_H_
+#define _DOUBLETRANSIENTMATPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleTransientMatParam: public DoubleMatParam{
+
+	public:
+		/*DoubleTransientMatParam constructors, destructors: {{{*/
+		DoubleTransientMatParam(int enum_type,IssmDouble* value,int M,int N);
+		/*}}}*/
+};
+#endif  /* _DOUBLETRANSIENTMATPARAM_H */
Index: /issm/trunk/src/c/classes/Params/DoubleVecParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleVecParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DoubleVecParam.cpp	(revision 15396)
@@ -0,0 +1,134 @@
+/*!\file DoubleVecParam.c
+ * \brief: implementation of the DoubleVecParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*DoubleVecParam constructors and destructor*/
+/*FUNCTION DoubleVecParam::DoubleVecParam(){{{*/
+DoubleVecParam::DoubleVecParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::DoubleVecParam(int enum_type,IssmDoubleVec values,int M){{{*/
+DoubleVecParam::DoubleVecParam(int in_enum_type,IssmDouble* in_values, int in_M){
+
+	enum_type=in_enum_type;
+	M=in_M;
+
+	values=xNew<IssmDouble>(M);
+	xMemCpy<IssmDouble>(values,in_values,M);
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::~DoubleVecParam(){{{*/
+DoubleVecParam::~DoubleVecParam(){
+	xDelete<IssmDouble>(values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleVecParam::Echo {{{*/
+void DoubleVecParam::Echo(void){
+
+	_printf_("DoubleVecParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   vector size: " << this->M << "\n");
+
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::DeepEcho{{{*/
+void DoubleVecParam::DeepEcho(void){
+
+	int i;
+
+	_printf_("DoubleVecParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   vector size: " << this->M << "\n");
+	for(i=0;i<this->M;i++){
+		_printf_(i << " " << this->values[i] << "\n");
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::Id{{{*/
+int    DoubleVecParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleVecParam::ObjectEnum{{{*/
+int DoubleVecParam::ObjectEnum(void){
+
+	return DoubleVecParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::copy{{{*/
+Object* DoubleVecParam::copy() {
+
+	return new DoubleVecParam(this->enum_type,this->values,this->M);
+
+}
+/*}}}*/
+
+/*DoubleVecParam virtual functions definitions: */
+/*FUNCTION DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){{{*/
+void  DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){
+	IssmDouble* output=NULL;
+	int M;
+
+	M=this->M;
+	output=xNew<IssmDouble>(M);
+	xMemCpy<IssmDouble>(output,values,M);
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	*pIssmDoublearray=output;
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){{{*/
+void  DoubleVecParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){
+	IssmDouble* output=NULL;
+	int M;
+	int N;
+
+	N=1;
+	M=this->M;
+	output=xNew<IssmDouble>(M);
+	xMemCpy<IssmDouble>(output,values,M);
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	if(pN) *pN=N;
+	*pIssmDoublearray=output;
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::GetParameterValue(int** pintarray,int* pM){{{*/
+void  DoubleVecParam::GetParameterValue(int** pintarray,int* pM){
+	_error_("DoubleVec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::GetParameterName{{{*/
+void DoubleVecParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::SetValue{{{*/
+void  DoubleVecParam::SetValue(IssmDouble* IssmDoublearray,int in_M){
+
+	/*avoid leak: */
+	xDelete<IssmDouble>(this->values);
+
+	this->values=xNew<IssmDouble>(in_M);
+	xMemCpy<IssmDouble>(this->values,IssmDoublearray,in_M);
+
+	this->M=in_M;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/DoubleVecParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/DoubleVecParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/DoubleVecParam.h	(revision 15396)
@@ -0,0 +1,75 @@
+/*! \file DoubleVecParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DOUBLEVECPARAM_H_
+#define _DOUBLEVECPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleVecParam: public Param{
+
+	private: 
+		int         enum_type;
+		IssmDouble *values;
+		int         M;
+
+	public:
+		/*DoubleVecParam constructors, destructors: {{{*/
+		DoubleVecParam();
+		DoubleVecParam(int enum_type,IssmDouble* values,int M);
+		~DoubleVecParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param virtual functions definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");};
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM);
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN);
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M);
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif  /* _DOUBLEVECPARAM_H */
Index: /issm/trunk/src/c/classes/Params/FileParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/FileParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/FileParam.cpp	(revision 15396)
@@ -0,0 +1,73 @@
+/*!\file FileParam.c
+ * \brief: implementation of the FileParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*FileParam constructors and destructor*/
+/*FUNCTION FileParam::FileParam(){{{*/
+FileParam::FileParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION FileParam::FileParam(int enum_type,FILE *value){{{*/
+FileParam::FileParam(int in_enum_type,FILE* in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION FileParam::~FileParam(){{{*/
+FileParam::~FileParam(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION FileParam::Echo {{{*/
+void FileParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION FileParam::DeepEcho{{{*/
+void FileParam::DeepEcho(void){
+
+	_printf_("FileParam:\n");
+	_printf_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   value: " << this->value << "\n");
+}
+/*}}}*/
+/*FUNCTION FileParam::Id{{{*/
+int    FileParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION FileParam::ObjectEnum{{{*/
+int FileParam::ObjectEnum(void){
+
+	return FileParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION FileParam::copy{{{*/
+Object* FileParam::copy() {
+
+	return new FileParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*FileParam virtual functions definitions: */
+/*FUNCTION FileParam::GetParameterName{{{*/
+void FileParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/FileParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/FileParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/FileParam.h	(revision 15396)
@@ -0,0 +1,75 @@
+/*! \file FileParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _FILEPARAM_H_
+#define _FILEPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class FileParam: public Param{
+
+	private: 
+		int   enum_type;
+		FILE* value;
+
+	public:
+		/*FileParam constructors, destructors: {{{*/
+		FileParam();
+		FileParam(int enum_type,FILE* fid);
+		~FileParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){  _error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){*pfid=value;};
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/trunk/src/c/classes/Params/GenericParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/GenericParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/GenericParam.h	(revision 15396)
@@ -0,0 +1,96 @@
+/*
+ * GenericParam.h
+ *
+ *  Created on: Aug 29, 2012
+ *      Author: utke
+ */
+
+#ifndef GENERICPARAM_H_
+#define GENERICPARAM_H_
+
+/*Headers:*/
+#ifdef HAVE_CONFIG_H
+        #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./Param.h"
+#include "../../shared/shared.h"
+
+/**
+ * here we have a class that holds an instance of P
+ * but because it should live side by side with
+ * the other instances derived from Param it - unfortunately -
+ * inherits all the accessors that are useless in this context
+ */
+template <class P> class GenericParam: public Param{
+
+        private:
+                P myP;
+                int myEnumVal;
+
+        public:
+                /*GenericParam constructors, destructors: {{{*/
+                GenericParam(int enumVal) : myEnumVal(enumVal){};
+                ~GenericParam(){};
+                /*}}}*/
+                /*Object virtual functions definitions:{{{ */
+                // unfortunately,  having to implement such a printer method implies
+                // that any structured P must provide the friend << operator
+                void  DeepEcho() {
+                  _printf_("GenericParam:\n");
+                  _printf_("   enum:  " << myEnumVal << " (" << EnumToStringx(myEnumVal) << ")\n");
+                  _printf_("   value: " << myP << "\n");;
+                }
+                void  Echo() {DeepEcho();};
+                int   Id(){ return -1; };
+                int   ObjectEnum() {return AdolcParamEnum;};
+
+                // the "copy"  has to implement the base class abstract function
+                // but I would prefer to drop this not to hide a "new" in here because
+                // it does not clarify  ownership of the newed up instance...
+                // use the default copy constructor instead
+                Object* copy() { return new GenericParam<P>(*this); };
+                /*}}}*/
+                /*Param vritual function definitions: {{{*/
+                int   InstanceEnum(){return myEnumVal;}
+                void GetParameterName(char**pname) {EnumToStringx(pname,this->myEnumVal);}
+
+                P& GetParameterValue() { return myP;}
+                const P& GetParameterValue()const { return myP;};
+
+                // none of these apply ...
+                void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a bool");}
+                void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return an integer");}
+                void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return an array of integers");}
+                void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return an array of integers");}
+                void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble");}
+                void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble for a given time");}
+                void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a string");}
+                void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a string array");}
+                void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble array");}
+                void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble array");}
+                void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a matrix array");}
+                void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a Vec");}
+                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a Mat");}
+                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a FILE");}
+				void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a DataSet");}
+
+                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a bool");}
+                void  SetValue(int integer){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an integer");}
+                void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an int array");}
+                void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an int array");}
+                void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an IssmDouble");}
+                void  SetValue(char* string){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a string");}
+                void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a string array");}
+                void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a IssmDouble array");}
+                void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a IssmDouble array");}
+                void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a Vec");}
+                void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a Mat");}
+                void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a FILE");}
+                void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an array of matrices");}
+
+                /*}}}*/
+};
+
+#endif /* GENERICPARAM_H_ */
Index: /issm/trunk/src/c/classes/Params/IntMatParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/IntMatParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/IntMatParam.cpp	(revision 15396)
@@ -0,0 +1,115 @@
+/*!\file IntMatParam.c
+ * \brief: implementation of the IntMatParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*IntMatParam constructors and destructor*/
+/*FUNCTION IntMatParam::IntMatParam(){{{*/
+IntMatParam::IntMatParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION IntMatParam::IntMatParam(int enum_type,IssmIntMat value){{{*/
+IntMatParam::IntMatParam(int in_enum_type,int* in_value, int in_M,int in_N){
+
+	enum_type=in_enum_type;
+	M=in_M;
+	N=in_N;
+
+	value=xNew<int>(M*N);
+	xMemCpy<int>(value,in_value,M*N);
+}
+/*}}}*/
+/*FUNCTION IntMatParam::~IntMatParam(){{{*/
+IntMatParam::~IntMatParam(){
+	xDelete<int>(value);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IntMatParam::Echo {{{*/
+void IntMatParam::Echo(void){
+
+	_printf_("IntMatParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   matrix size: " << this->M << "x" << this->N << "\n");
+
+}
+/*}}}*/
+/*FUNCTION IntMatParam::DeepEcho{{{*/
+void IntMatParam::DeepEcho(void){
+
+	int i,j;
+
+	_printf_("IntMatParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   matrix size: " << this->M << "x" << this->N << "\n");
+	for(i=0;i<this->M;i++){
+		for(i=0;i<this->N;i++){
+			_printf_("(" << i << "," << j << ") " << *(this->value+N*i+j) << "\n");
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION IntMatParam::Id{{{*/
+int    IntMatParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntMatParam::ObjectEnum{{{*/
+int IntMatParam::ObjectEnum(void){
+
+	return IntMatParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION IntMatParam::copy{{{*/
+Object* IntMatParam::copy() {
+
+	return new IntMatParam(this->enum_type,this->value,this->M,this->N);
+
+}
+/*}}}*/
+
+/*IntMatParam virtual functions definitions: */
+/*FUNCTION IntMatParam::GetParameterValue{{{*/
+void  IntMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){
+	int* output=NULL;
+
+	output=xNew<int>(M*N);
+	xMemCpy<int>(output,value,M*N);
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	if(pN) *pN=N;
+	*pintarray=output;
+}
+/*}}}*/
+/*FUNCTION IntMatParam::GetParameterName{{{*/
+void IntMatParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION IntMatParam::SetValue{{{*/
+void  IntMatParam::SetValue(int* intarray,int in_M,int in_N){
+
+	/*avoid leak: */
+	xDelete<int>(this->value);
+
+	this->value=xNew<int>(in_M*in_N);
+	xMemCpy<int>(this->value,intarray,in_M*in_N);
+
+	this->M=in_M;
+	this->N=in_N;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/IntMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/IntMatParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/IntMatParam.h	(revision 15396)
@@ -0,0 +1,77 @@
+/*! \file IntMatParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _INTMATPARAM_H_
+#define _INTMATPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class IntMatParam: public Param{
+
+	private: 
+		int enum_type;
+		int* value;
+		int M;
+		int N;
+
+	public:
+		/*IntMatParam constructors, destructors: {{{*/
+		IntMatParam();
+		IntMatParam(int enum_type,int* value,int M,int N);
+		~IntMatParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");};
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");};
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");};
+		void  SetValue(int* intarray,int M,int N);
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTMATPARAM_H */
Index: /issm/trunk/src/c/classes/Params/IntParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/IntParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/IntParam.cpp	(revision 15396)
@@ -0,0 +1,73 @@
+/*!\file IntParam.c
+ * \brief: implementation of the IntParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*IntParam constructors and destructor*/
+/*FUNCTION IntParam::IntParam(){{{*/
+IntParam::IntParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION IntParam::IntParam(int enum_type,IssmInt value){{{*/
+IntParam::IntParam(int in_enum_type,IssmInt in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION IntParam::~IntParam(){{{*/
+IntParam::~IntParam(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IntParam::Echo {{{*/
+void IntParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION IntParam::DeepEcho{{{*/
+void IntParam::DeepEcho(void){
+
+	_printf_("IntParam:\n");
+	_printf_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   value: " << this->value << "\n");
+}
+/*}}}*/
+/*FUNCTION IntParam::Id{{{*/
+int    IntParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntParam::ObjectEnum{{{*/
+int IntParam::ObjectEnum(void){
+
+	return IntParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION IntParam::copy{{{*/
+Object* IntParam::copy() {
+
+	return new IntParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*IntParam virtual functions definitions: */
+/*FUNCTION IntParam::GetParameterName{{{*/
+void IntParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/IntParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/IntParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/IntParam.h	(revision 15396)
@@ -0,0 +1,76 @@
+/*! \file IntParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _INTPARAM_H_
+#define _INTPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class IntParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		IssmInt value;
+
+	public:
+		/*IntParam constructors, destructors: {{{*/
+		IntParam();
+		IntParam(int enum_type,IssmInt value);
+		~IntParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){*pinteger=value;}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a bool");}
+		void  SetValue(int integer){this->value=integer;}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an IssmDouble");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/trunk/src/c/classes/Params/IntVecParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/IntVecParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/IntVecParam.cpp	(revision 15396)
@@ -0,0 +1,131 @@
+/*!\file IntVecParam.c
+ * \brief: implementation of the IntVecParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*IntVecParam constructors and destructor*/
+/*FUNCTION IntVecParam::IntVecParam(){{{*/
+IntVecParam::IntVecParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::IntVecParam(int enum_type,int* values,int M){{{*/
+IntVecParam::IntVecParam(int in_enum_type,int* in_values, int in_M){
+
+	enum_type=in_enum_type;
+	M=in_M;
+
+	if(M){
+		values=xNew<int>(M);
+		xMemCpy<int>(values,in_values,M);
+	}
+	else values=NULL;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::IntVecParam(int enum_type,IssmDouble* values,int M){{{*/
+IntVecParam::IntVecParam(int in_enum_type,IssmDouble* in_values, int in_M){
+
+	enum_type=in_enum_type;
+	M=in_M;
+
+	if(M){
+		values=xNew<int>(M);
+		for(int i=0;i<in_M;i++) values[i]=reCast<int>(in_values[i]);
+	}
+	else values=NULL;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::~IntVecParam(){{{*/
+IntVecParam::~IntVecParam(){
+	xDelete<int>(values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IntVecParam::Echo {{{*/
+void IntVecParam::Echo(void){
+
+	_printf_("IntVecParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   vector size: " << this->M << "\n");
+
+}
+/*}}}*/
+/*FUNCTION IntVecParam::DeepEcho{{{*/
+void IntVecParam::DeepEcho(void){
+
+	int i;
+
+	_printf_("IntVecParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   vector size: " << this->M << "\n");
+	for(i=0;i<this->M;i++){
+		_printf_(i << " " << this->values[i] << "\n");
+	}
+}
+/*}}}*/
+/*FUNCTION IntVecParam::Id{{{*/
+int    IntVecParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntVecParam::ObjectEnum{{{*/
+int IntVecParam::ObjectEnum(void){
+
+	return IntVecParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION IntVecParam::copy{{{*/
+Object* IntVecParam::copy() {
+
+	return new IntVecParam(this->enum_type,this->values,this->M);
+
+}
+/*}}}*/
+
+/*IntVecParam virtual functions definitions: */
+/*FUNCTION IntVecParam::GetParameterValue{{{*/
+void  IntVecParam::GetParameterValue(int** pintarray,int* pM){
+	int* output=NULL;
+
+	if(M){
+		output=xNew<int>(M);
+		xMemCpy<int>(output,values,M);
+	}
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	*pintarray=output;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::GetParameterName{{{*/
+void IntVecParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION IntVecParam::SetValue{{{*/
+void  IntVecParam::SetValue(int* intarray,int in_M){
+
+	/*avoid leak: */
+	xDelete<int>(this->values);
+
+	if(in_M){
+		this->values=xNew<int>(in_M);
+		xMemCpy<int>(this->values,intarray,in_M);
+	}
+	else this->values=NULL;
+
+	this->M=in_M;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/IntVecParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/IntVecParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/IntVecParam.h	(revision 15396)
@@ -0,0 +1,76 @@
+/*! \file IntVecParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _INTVECPARAM_H_
+#define _INTVECPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class IntVecParam: public Param{
+
+	private: 
+		int enum_type;
+		int* values;
+		int M;
+
+	public:
+		/*IntVecParam constructors, destructors: {{{*/
+		IntVecParam();
+		IntVecParam(int enum_type,int* values,int M);
+		IntVecParam(int enum_type,IssmDouble* values,int M);
+		~IntVecParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param virtual functions definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array (maybe in serial?)");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M);
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif
Index: /issm/trunk/src/c/classes/Params/MatrixParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/MatrixParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/MatrixParam.cpp	(revision 15396)
@@ -0,0 +1,100 @@
+/*!\file MatrixParam.c
+ * \brief: implementation of the MatrixParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*MatrixParam constructors and destructor*/
+/*FUNCTION MatrixParam::MatrixParam(){{{*/
+MatrixParam::MatrixParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION MatrixParam::MatrixParam(int enum_type,Matrix<IssmDouble>* value){{{*/
+MatrixParam::MatrixParam(int in_enum_type,Matrix<IssmDouble>* in_value){
+
+	enum_type=in_enum_type;
+	value=NULL;
+
+	if(in_value){
+		value=in_value->Duplicate();
+	}
+}
+/*}}}*/
+/*FUNCTION MatrixParam::~MatrixParam(){{{*/
+MatrixParam::~MatrixParam(){
+	delete value;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION MatrixParam::Echo {{{*/
+void MatrixParam::Echo(void){
+
+	_printf_("MatrixParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+
+}
+/*}}}*/
+/*FUNCTION MatrixParam::DeepEcho{{{*/
+void MatrixParam::DeepEcho(void){
+
+	_printf_("MatrixParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	this->value->Echo();
+}
+/*}}}*/
+/*FUNCTION MatrixParam::Id{{{*/
+int    MatrixParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION MatrixParam::ObjectEnum{{{*/
+int MatrixParam::ObjectEnum(void){
+
+	return MatrixParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION MatrixParam::copy{{{*/
+Object* MatrixParam::copy() {
+
+	return new MatrixParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*MatrixParam virtual functions definitions: */
+/*FUNCTION MatrixParam::GetParameterValue{{{*/
+void  MatrixParam::GetParameterValue(Matrix<IssmDouble>** poutput){
+	Matrix<IssmDouble>* output=NULL;
+
+	if(value){
+		output=value->Duplicate();
+	}
+	*poutput=output;
+}
+/*}}}*/
+/*FUNCTION MatrixParam::GetParameterName{{{*/
+void MatrixParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION MatrixParam::SetValue{{{*/
+void  MatrixParam::SetValue(Matrix<IssmDouble>* matrix){
+
+	/*avoid leak: */
+	delete value;
+
+	/*copy: */
+	value=matrix->Duplicate();
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/MatrixParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/MatrixParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/MatrixParam.h	(revision 15396)
@@ -0,0 +1,76 @@
+/*! \file MatrixParam.h 
+ *  \brief: header file for MatrixParam object
+ */
+
+#ifndef _MATRIXPARAM_H_
+#define _MATRIXPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class MatrixParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		Matrix<IssmDouble>* value;
+
+	public:
+		/*MatrixParam constructors, destructors: {{{*/
+		MatrixParam();
+		MatrixParam(int enum_type,Matrix<IssmDouble>* value);
+		~MatrixParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** poutput);
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat);
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _MATRIXPARAM_H */
Index: /issm/trunk/src/c/classes/Params/Param.h
===================================================================
--- /issm/trunk/src/c/classes/Params/Param.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/Param.h	(revision 15396)
@@ -0,0 +1,59 @@
+/*!\file:  Param.h
+ * \brief abstract class for Param object
+ */ 
+
+#ifndef _PARAM_H_
+#define _PARAM_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../datastructures/datastructures.h"
+#include "../Node.h"
+/*}}}*/
+
+class Param: public Object{
+
+	public: 
+		virtual        ~Param(){};
+
+		/*Virtual functions:*/
+		virtual int   InstanceEnum()=0;
+		virtual void  GetParameterValue(bool* pbool)=0;
+		virtual void  GetParameterValue(int* pinteger)=0;
+		virtual void  GetParameterValue(int** pintarray,int* pM)=0;
+		virtual void  GetParameterValue(int** pintarray,int* pM,int* pN)=0;
+		virtual void  GetParameterValue(IssmDouble* pIssmDouble)=0;
+		virtual void  GetParameterValue(IssmDouble* pdouble,IssmDouble time)=0;
+		virtual void  GetParameterValue(char** pstring)=0;
+		virtual void  GetParameterValue(char*** pstringarray,int* pM)=0;
+		virtual void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM)=0;
+		virtual void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN)=0;
+		virtual void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims)=0;
+		virtual void  GetParameterValue(Vector<IssmDouble>** pvec)=0;
+		virtual void  GetParameterValue(Matrix<IssmDouble>** pmat)=0;
+		virtual void  GetParameterValue(FILE** pfid)=0;
+		virtual void  GetParameterValue(DataSet** pdataset)=0;
+
+		virtual void  SetValue(bool boolean)=0;
+		virtual void  SetValue(int integer)=0;
+		virtual void  SetValue(IssmDouble scalar)=0;
+		virtual void  SetValue(char* string)=0;
+		virtual void  SetValue(char** stringarray,int M)=0;
+		virtual void  SetValue(IssmDouble* IssmDoublearray,int M)=0;
+		virtual void  SetValue(IssmDouble* pIssmDoublearray,int M,int N)=0;
+		virtual void  SetValue(int* intarray,int M)=0;
+		virtual void  SetValue(int* pintarray,int M,int N)=0;
+		virtual void  SetValue(Vector<IssmDouble>* vec)=0;
+		virtual void  SetValue(Matrix<IssmDouble>* mat)=0;
+		virtual void  SetValue(FILE* fid)=0;
+		virtual void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array)=0;
+		virtual void  GetParameterName(char**pname)=0;
+};
+#endif
Index: /issm/trunk/src/c/classes/Params/Parameters.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 15396)
@@ -0,0 +1,591 @@
+/*
+ * \file Parameters.cpp
+ * \brief: Implementation of the Parameters class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <vector>
+#include <functional>
+#include <algorithm>
+#include <iostream>
+
+#include "./Parameters.h"
+#include "./Param.h"
+
+#include "./BoolParam.h"
+#include "./DoubleMatParam.h"
+#include "./DoubleParam.h"
+#include "./DoubleVecParam.h"
+#include "./IntParam.h"
+#include "./IntVecParam.h"
+#include "./IntMatParam.h"
+#include "./FileParam.h"
+#include "./MatrixParam.h"
+#include "./VectorParam.h"
+#include "./StringArrayParam.h"
+#include "./StringParam.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Parameters::Parameters(){{{*/
+Parameters::Parameters(){
+	enum_type=ParametersEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Parameters::~Parameters(){{{*/
+Parameters::~Parameters(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Parameters::Exist{{{*/
+bool Parameters::Exist(int enum_type){
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type) return true;
+	}
+	return false;
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(bool* pbool,int enum_type){{{*/
+void Parameters::FindParam(bool* pbool,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pbool);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(int* pinteger,int enum_type){{{*/
+void Parameters::FindParam(int* pinteger,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pinteger);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(IssmDouble* pscalar, int enum_type){{{*/
+void Parameters::FindParam(IssmDouble* pscalar, int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pscalar);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time){{{*/
+void Parameters::FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pscalar,time);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(char** pstring,int enum_type){{{*/
+void Parameters::FindParam(char** pstring,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pstring);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){{{*/
+void Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pstringarray,pM);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(int** pintarray,int* pM,int enum_type){{{*/
+void Parameters::FindParam(int** pintarray,int* pM, int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pintarray,pM);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(int** pintarray,int* pM,int* pN,int enum_type){{{*/
+void Parameters::FindParam(int** pintarray,int* pM,int *pN,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pintarray,pM,pN);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM,int enum_type){{{*/
+void Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM, int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pIssmDoublearray,pM);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM, int* pN,int enum_type){{{*/
+void Parameters::FindParam(IssmDouble** pIssmDoublearray,int* pM, int* pN,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pIssmDoublearray,pM,pN);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(IssmDouble*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){{{*/
+void Parameters::FindParam(IssmDouble*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(parray,pM,pmdims_array,pndims_array);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){{{*/
+void Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pvec);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){{{*/
+void Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pmat);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(FILE** pfid,int enum_type){{{*/
+void Parameters::FindParam(FILE** pfid,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pfid);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(DataSet** pdataset,int enum_type){{{*/
+void Parameters::FindParam(DataSet** pdataset,int enum_type){ 
+	_assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pdataset);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+
+/*FUNCTION Parameters::SetParam(bool boolean,int enum_type);{{{*/
+void   Parameters::SetParam(bool boolean,int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(boolean); //already exists, just set it.
+	else this->AddObject(new BoolParam(enum_type,boolean)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(int integer,int enum_type);{{{*/
+void   Parameters::SetParam(int integer,int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(integer); //already exists, just set it.
+	else this->AddObject(new IntParam(enum_type,integer)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(IssmDouble scalar,int enum_type);{{{*/
+void   Parameters::SetParam(IssmDouble scalar,int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(scalar); //already exists, just set it.
+	else this->AddObject(new DoubleParam(enum_type,scalar)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(char* string,int enum_type);{{{*/
+void   Parameters::SetParam(char* string,int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(string); //already exists, just set it.
+	else this->AddObject(new StringParam(enum_type,string)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(char** stringarray,int M, int enum_type);{{{*/
+void   Parameters::SetParam(char** stringarray,int M, int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(stringarray,M); //already exists, just set it.
+	else this->AddObject(new StringArrayParam(enum_type,stringarray,M)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(IssmDouble* IssmDoublearray,int M,int enum_type);{{{*/
+void   Parameters::SetParam(IssmDouble* IssmDoublearray,int M, int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(IssmDoublearray,M); //already exists, just set it.
+	else this->AddObject(new DoubleVecParam(enum_type,IssmDoublearray,M)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(IssmDouble* IssmDoublearray,int M,int N, int enum_type);{{{*/
+void   Parameters::SetParam(IssmDouble* IssmDoublearray,int M, int N, int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(IssmDoublearray,M,N); //already exists, just set it.
+	else this->AddObject(new DoubleMatParam(enum_type,IssmDoublearray,M,N)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(int* intarray,int M,int enum_type);{{{*/
+void   Parameters::SetParam(int* intarray,int M, int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(intarray,M); //already exists, just set it.
+	else this->AddObject(new IntVecParam(enum_type,intarray,M)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(int* intarray,int M,int N, int enum_type);{{{*/
+void   Parameters::SetParam(int* intarray,int M, int N, int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(intarray,M,N); //already exists, just set it.
+	else this->AddObject(new IntMatParam(enum_type,intarray,M,N)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(Vector<IssmDouble>* vector,int enum_type);{{{*/
+void   Parameters::SetParam(Vector<IssmDouble>* vector,int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(vector); //already exists, just set it.
+	else this->AddObject(new VectorParam(enum_type,vector)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(Matrix<IssmDouble>* matrix,int enum_type);{{{*/
+void   Parameters::SetParam(Matrix<IssmDouble>* matrix,int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(matrix); //already exists, just set it.
+	else this->AddObject(new MatrixParam(enum_type,matrix)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(FILE* fid,int enum_type);{{{*/
+void   Parameters::SetParam(FILE* fid,int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+
+	if(param) param->SetValue(fid); //already exists, just set it.
+	else this->AddObject(new FileParam(enum_type,fid)); //just add the new parameter.
+}
+/*}}}*/
+
+/*FUNCTION Parameters::FindParamObject{{{*/
+Object* Parameters::FindParamObject(int enum_type){
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			return (*object);
+		}
+	}
+	return NULL;
+}
+/*}}}*/
+
+/*Methods relating to parameters: */
+char* OptionsFromAnalysis(Parameters* parameters,int analysis_type){ /*{{{*/
+
+	/* figure out ISSM options for current analysis, return a string. */ 
+
+	/*output: */
+	char*   outstring=NULL;
+
+	/*intermediary: */
+	int          dummy;
+	IssmDouble  *analyses    = NULL;
+	char       **strings     = NULL;
+	char        *string      = NULL;
+	int          numanalyses;
+	int          found       = -1;
+	int          i;
+
+	numanalyses=0;
+	parameters->FindParam(&strings,&numanalyses,ToolkitsOptionsStringsEnum);
+
+	parameters->FindParam(&analyses,&dummy,ToolkitsOptionsAnalysesEnum);
+
+	if(numanalyses==0)return NULL; //we did not find petsc options, don't bother.
+
+	/*ok, go through analyses and figure out if it corresponds to our analysis_type: */
+	for(i=0;i<numanalyses;i++){
+		if(analyses[i]==analysis_type){
+			found=i;
+			break;
+		}
+	}
+	if(found==-1){
+		/*still haven't found a list of petsc options, go find the default one, for analysis type NoneAnalysisEnum: */
+		for(i=0;i<numanalyses;i++){
+			if(analyses[i]==DefaultAnalysisEnum){
+				found=i;
+				break;
+			}
+		}
+	}
+	if (found==-1){
+		_error_("could find neither a default analysis nor analysis " << EnumToStringx(analysis_type));
+	}
+
+	/*ok, grab the option string: */
+	outstring=xNew<char>(strlen(strings[found])+1);
+	strcpy(outstring,strings[found]);
+
+	/*Free ressources*/
+	xDelete<IssmDouble>(analyses);
+	for(i=0;i<numanalyses;i++){
+		string=strings[i];
+		xDelete<char>(string);
+	}
+	xDelete<char*>(strings);
+	return outstring;
+} 
+/*}}}*/
+void ToolkitsOptionsFromAnalysis(Parameters* parameters,int analysis_type){ /*{{{*/
+
+	/*!\file:  ToolkitsOptionsFromAnalysis.cpp
+	 * \brief: for each analysis, setup the issmoptions string. 
+	 * This is mainly for the case where we run our toolkits using petsc. In this case, we need to 
+	 * plug our toolkits options directly into the petsc options database. This is the case for each analysis type 
+	 * and parameters
+	 */ 
+
+	char* options=NULL;
+
+	/*Recover first the options string for this analysis: */
+	options=OptionsFromAnalysis(parameters,analysis_type);
+
+	/*Initialize our Toolkit Options: */
+	ToolkitOptions::Init(options);
+
+	#ifdef _HAVE_PETSC_
+		/*In case we are using PETSC, we do not rely on issmoptions. Instead, we dump issmoptions into the Petsc 
+		 * options database: */
+
+		#if _PETSC_MAJOR_ == 2 
+		PetscOptionsDestroy();
+		PetscOptionsCreate();
+		//PetscOptionsCheckInitial_Private();
+		//PetscOptionsCheckInitial_Components();
+		PetscOptionsSetFromOptions();
+		PetscOptionsInsertMultipleString(options); //our patch
+		#else
+		PetscOptionsSetFromOptions();
+		PetscOptionsClear();
+		//PetscOptionsSetFromOptions();
+		PetscOptionsInsertMultipleString(options); //our patch
+		#endif
+
+	#endif
+
+	xDelete<char>(options);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/Parameters.h
===================================================================
--- /issm/trunk/src/c/classes/Params/Parameters.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/Parameters.h	(revision 15396)
@@ -0,0 +1,63 @@
+#ifndef _CONTAINER_PARAMETERS_H_
+#define  _CONTAINER_PARAMETERS_H_
+#include <stdio.h>
+
+/*forward declarations */
+template <class doublematrix> class Matrix;
+template <class doubletype> class Vector;
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+
+/*!\brief Declaration of Parameters class.  
+ *
+ * Declaration of Parameters class.  Parameters are vector lists (Containers) of Parameter objects.
+ */ 
+class Parameters: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/ 
+		Parameters();
+		~Parameters();
+
+		/*numerics*/
+		bool  Exist(int enum_type);
+
+		void  FindParam(bool* pinteger,int enum_type);
+		void  FindParam(int* pinteger,int enum_type);
+		void  FindParam(IssmDouble* pscalar, int enum_type);
+		void  FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time);
+		void  FindParam(char** pstring,int enum_type);
+		void  FindParam(char*** pstringarray,int* pM,int enum_type);
+		void  FindParam(int** pintarray,int* pM,int enum_type);
+		void  FindParam(int** pintarray,int* pM,int* PN,int enum_type);
+		void  FindParam(IssmDouble** pIssmDoublearray,int* pM,int enum_type);
+		void  FindParam(IssmDouble** pIssmDoublearray,int* pM,int* pN,int enum_type);
+		void  FindParam(IssmDouble*** parray,int* pM, int** pmdims_array,int** pndims_array,int enum_type);
+		void  FindParam(Vector<IssmDouble>** pvec,int enum_type);
+		void  FindParam(Matrix<IssmDouble>** pmat,int enum_type);
+		void  FindParam(FILE** pfid,int enum_type);
+		void  FindParam(DataSet** pdataset, int enum_type);
+
+		void  SetParam(bool boolean,int enum_type);
+		void  SetParam(int integer,int enum_type);
+		void  SetParam(IssmDouble scalar, int enum_type);
+		void  SetParam(char* string,int enum_type);
+		void  SetParam(char** stringarray,int M,int enum_type);
+		void  SetParam(IssmDouble* IssmDoublearray,int M,int enum_type);
+		void  SetParam(IssmDouble* IssmDoublearray,int M,int N,int enum_type);
+		void  SetParam(int* intarray,int M,int enum_type);
+		void  SetParam(int* intarray,int M,int N,int enum_type);
+		void  SetParam(Vector<IssmDouble>* vec,int enum_type);
+		void  SetParam(Matrix<IssmDouble>* mat,int enum_type);
+		void  SetParam(FILE* fid,int enum_type);
+
+		Object* FindParamObject(int enum_type);
+
+};
+
+/*Methods relating to parameters: */
+char       *OptionsFromAnalysis(Parameters *parameters,int analysis_type);
+void        ToolkitsOptionsFromAnalysis(Parameters* parameters,int analysis_type);
+
+#endif //ifndef _PARAMETERS_H_
Index: /issm/trunk/src/c/classes/Params/StringArrayParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/StringArrayParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/StringArrayParam.cpp	(revision 15396)
@@ -0,0 +1,163 @@
+/*!\file StringArrayParam.c
+ * \brief: implementation of the StringArrayParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*StringArrayParam constructors and destructor*/
+/*FUNCTION StringArrayParam::StringArrayParam(){{{*/
+StringArrayParam::StringArrayParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::StringArrayParam(int enum_type,char** in_values,int in_numstrings){{{*/
+StringArrayParam::StringArrayParam(int in_enum_type,char** in_values, int in_numstrings){
+
+	int i;
+	int size;
+
+	enum_type=in_enum_type;
+	numstrings=in_numstrings;
+
+	if(numstrings){
+		value=xNew<char*>(numstrings);
+		for(i=0;i<numstrings;i++){
+			char* string=NULL;
+			size=strlen(in_values[i])+1;
+			string=xNew<char>(size);
+			xMemCpy<char>(string,in_values[i],size);
+			value[i]=string;
+		}
+	}
+	else value=NULL;
+
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::~StringArrayParam(){{{*/
+StringArrayParam::~StringArrayParam(){
+
+	int i;
+
+	char* string=NULL;
+	for(i=0;i<this->numstrings;i++){
+		string=value[i];
+		xDelete<char>(string);
+	}
+	xDelete<char*>(value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION StringArrayParam::Echo {{{*/
+void StringArrayParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::DeepEcho{{{*/
+void StringArrayParam::DeepEcho(void){
+
+	int i;
+	char* string=NULL;
+
+	_printf_("StringArrayParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	for(i=0;i<this->numstrings;i++){
+		string=this->value[i];
+		_printf_("   " << i << ": " << string << "\n");
+	}
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::Id{{{*/
+int    StringArrayParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION StringArrayParam::ObjectEnum{{{*/
+int StringArrayParam::ObjectEnum(void){
+
+	return StringArrayParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::copy{{{*/
+Object* StringArrayParam::copy() {
+
+	return new StringArrayParam(this->enum_type,this->value,this->numstrings);
+
+}
+/*}}}*/
+
+/*StringArrayParam virtual functions definitions: */
+/*FUNCTION StringArrayParam::GetParameterValue{{{*/
+void  StringArrayParam::GetParameterValue(char*** pstringarray,int* pM){
+
+	int   i;
+	char** outstrings=NULL;
+	int   M;
+	char* string=NULL;
+	char* string2=NULL;
+	int   stringsize;
+
+	M=this->numstrings;
+	if(this->numstrings){
+		outstrings=xNew<char*>(this->numstrings);
+
+		for(i=0;i<this->numstrings;i++){
+			string=this->value[i];
+			stringsize=strlen(string)+1;
+
+			string2=xNew<char>(stringsize);
+			xMemCpy<char>(string2,string,stringsize);
+
+			outstrings[i]=string2;
+		}
+	}
+	else outstrings=NULL;
+
+	/*Assign output pointers:*/
+	*pM=M;
+	*pstringarray=outstrings;
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::GetParameterName{{{*/
+void StringArrayParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::SetValue{{{*/
+void  StringArrayParam::SetValue(char** stringarray,int M){
+
+	int   i;
+	char *string     = NULL;
+	char *string2    = NULL;
+	int   stringsize;
+
+	/*first, avoid leak: */
+	for(i=0;i<this->numstrings;i++){
+		string=this->value[i];
+		xDelete<char>(string);
+	}
+	xDelete<char*>(this->value);
+
+	/*copy: */
+	this->numstrings=M;
+	this->value=xNew<char*>(this->numstrings);
+	for(i=0;i<this->numstrings;i++){
+		string=stringarray[i];
+		stringsize=strlen(string)+1;
+
+		string2=xNew<char>(stringsize);
+		xMemCpy<char>(string2,string,stringsize);
+
+		this->value[i]=string2;
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/StringArrayParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/StringArrayParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/StringArrayParam.h	(revision 15396)
@@ -0,0 +1,76 @@
+/*! \file StringArrayParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _STRINGARRAYPARAM_H_
+#define _STRINGARRAYPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class StringArrayParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int      enum_type;
+		char**   value;
+		int      numstrings;
+
+	public:
+		/*StringArrayParam constructors, destructors: {{{*/
+		StringArrayParam();
+		StringArrayParam(int enum_type,char** values, int numstrings);
+		~StringArrayParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM);
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Vec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M);
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif  /* _STRINGARRAYPARAM_H */
Index: /issm/trunk/src/c/classes/Params/StringParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/StringParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/StringParam.cpp	(revision 15396)
@@ -0,0 +1,104 @@
+/*!\file StringParam.c
+ * \brief: implementation of the StringParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*StringParam constructors and destructor*/
+/*FUNCTION StringParam::StringParam(){{{*/
+StringParam::StringParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION StringParam::StringParam(int enum_type,IssmString value){{{*/
+StringParam::StringParam(int in_enum_type,char* in_value){
+
+	enum_type=in_enum_type;
+	value=xNew<char>(strlen(in_value)+1);
+	xMemCpy<char>(value,in_value,(strlen(in_value)+1));
+
+}
+/*}}}*/
+/*FUNCTION StringParam::~StringParam(){{{*/
+StringParam::~StringParam(){
+	xDelete<char>(value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION StringParam::Echo {{{*/
+void StringParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION StringParam::DeepEcho{{{*/
+void StringParam::DeepEcho(void){
+	_printf_("StringParam:\n");
+	_printf_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   value: " << this->value << "\n");
+}
+/*}}}*/
+/*FUNCTION StringParam::Id{{{*/
+int    StringParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION StringParam::ObjectEnum{{{*/
+int StringParam::ObjectEnum(void){
+
+	return StringParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION StringParam::copy{{{*/
+Object* StringParam::copy() {
+
+	return new StringParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*StringParam virtual functions definitions: */
+/*FUNCTION StringParam::GetParameterValue{{{*/
+void  StringParam::GetParameterValue(char** pstring){
+
+	char* outstring=NULL;
+	int   stringsize;
+
+	stringsize=strlen(this->value)+1;
+
+	outstring=xNew<char>(stringsize);
+	xMemCpy<char>(outstring,this->value,stringsize);
+
+	*pstring=outstring;
+
+}
+/*}}}*/
+/*FUNCTION StringParam::GetParameterName{{{*/
+void StringParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION StringParam::SetValue{{{*/
+void  StringParam::SetValue(char* string){
+
+	int   stringsize;
+
+	/*avoid leak: */
+	xDelete<char>(this->value);
+
+	/*copy: */
+	stringsize=strlen(string)+1;
+	this->value=xNew<char>(stringsize);
+	xMemCpy<char>(this->value,string,stringsize);
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/StringParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/StringParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/StringParam.h	(revision 15396)
@@ -0,0 +1,76 @@
+/*! \file StringParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _STRINGPARAM_H_
+#define _STRINGPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class StringParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int   enum_type;
+		char *value;
+
+	public:
+		/*StringParam constructors, destructors: {{{*/
+		StringParam();
+		StringParam(int enum_type,char* value);
+		~StringParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring);
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string);
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _STRINGPARAM_H */
Index: /issm/trunk/src/c/classes/Params/TransientParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/TransientParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/TransientParam.cpp	(revision 15396)
@@ -0,0 +1,133 @@
+/*!\file TransientParam.c
+ * \brief: implementation of the TransientParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*TransientParam constructors and destructor*/
+/*FUNCTION TransientParam::TransientParam(){{{*/
+TransientParam::TransientParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION TransientParam::TransientParam(int enum_type,IssmDoubleMat value){{{*/
+TransientParam::TransientParam(int in_enum_type,IssmDouble* in_values,IssmDouble* in_time,int in_N){
+
+	_assert_(in_values && in_time);
+
+	enum_type=in_enum_type;
+	N=in_N;
+
+	values=xNew<IssmDouble>(N);
+	xMemCpy<IssmDouble>(values,in_values,N);
+
+	timesteps=xNew<IssmDouble>(N);
+	xMemCpy<IssmDouble>(timesteps,in_time,N);
+}
+/*}}}*/
+/*FUNCTION TransientParam::~TransientParam(){{{*/
+TransientParam::~TransientParam(){
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(timesteps);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION TransientParam::Echo {{{*/
+void TransientParam::Echo(void){
+
+	_printf_("TransientParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   size: " << this->N << "\n");
+
+}
+/*}}}*/
+/*FUNCTION TransientParam::DeepEcho{{{*/
+void TransientParam::DeepEcho(void){
+
+	_printf_("TransientParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   size: " << this->N << "\n");
+	for(int i=0;i<this->N;i++){
+		_printf_(   "time: " << this->timesteps[i] << " value: " << this->values[i] << "\n");
+	}
+}
+/*}}}*/
+/*FUNCTION TransientParam::Id{{{*/
+int    TransientParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TransientParam::ObjectEnum{{{*/
+int TransientParam::ObjectEnum(void){
+
+	return TransientParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION TransientParam::copy{{{*/
+Object* TransientParam::copy() {
+
+	return new TransientParam(this->enum_type,this->values,this->timesteps,this->N);
+
+}
+/*}}}*/
+
+/*TransientParam virtual functions definitions: */
+/*FUNCTION TransientParam::GetParameterValue(IssmDouble* pdouble,IssmDouble time){{{*/
+void  TransientParam::GetParameterValue(IssmDouble* pdouble,IssmDouble time){
+
+	IssmDouble output;
+	bool   found;
+
+	/*Ok, we have the time, go through the timesteps, and figure out which interval we 
+	 *fall within. Then interpolate the values on this interval: */
+	if(time<this->timesteps[0]){
+		/*get values for the first time: */
+		output=this->values[0];
+		found=true;
+	}
+	else if(time>this->timesteps[this->N-1]){
+		/*get values for the last time: */
+		output=this->values[this->N-1];
+		found=true;
+	}
+	else{
+		/*Find which interval we fall within: */
+		for(int i=0;i<this->N;i++){
+			if(time==this->timesteps[i]){
+				/*We are right on one step time: */
+				output=this->values[i];
+				found=true;
+				break; //we are done with the time interpolation.
+			}
+			else{
+				if(this->timesteps[i]<time && time<this->timesteps[i+1]){
+					/*ok, we have the interval ]i:i+1[. Interpolate linearly for now: */
+					IssmDouble deltat=this->timesteps[i+1]-this->timesteps[i];
+					IssmDouble alpha=(time-this->timesteps[i])/deltat;
+					output=(1.0-alpha)*this->values[i] + alpha*this->values[i+1];
+					found=true;
+					break;
+				}
+				else continue; //keep looking on the next interval
+			}
+		}
+	}
+	if(!found)_error_("did not find time interval on which to interpolate values");
+	*pdouble=output;
+}
+/*}}}*/
+/*FUNCTION TransientParam::GetParameterName{{{*/
+void TransientParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/TransientParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/TransientParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/TransientParam.h	(revision 15396)
@@ -0,0 +1,77 @@
+/*! \file TransientParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _TRANSIENTPARAM_H_
+#define _TRANSIENTPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class TransientParam: public Param{
+
+	protected: 
+		int         enum_type;
+		int         N;
+		IssmDouble *values;
+		IssmDouble *timesteps;
+
+	public:
+		/*TransientParam constructors, destructors: {{{*/
+		TransientParam();
+		TransientParam(int in_enum_type,IssmDouble* in_values,IssmDouble* in_time,int in_N);
+		~TransientParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time);
+		void  GetParameterValue(char** pstring){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _TRANSIENTPARAM_H */
Index: /issm/trunk/src/c/classes/Params/VectorParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/VectorParam.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/VectorParam.cpp	(revision 15396)
@@ -0,0 +1,104 @@
+/*!\file VectorParam.c
+ * \brief: implementation of the VectorParam object
+ */
+
+/*header files: */
+/*{{{*/
+#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"
+/*}}}*/
+
+/*VectorParam constructors and destructor*/
+/*FUNCTION VectorParam::VectorParam(){{{*/
+VectorParam::VectorParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION VectorParam::VectorParam(int enum_type,IssmVector value){{{*/
+VectorParam::VectorParam(int in_enum_type,Vector<IssmDouble>* in_value){
+
+	enum_type=in_enum_type;
+
+	value=NULL;
+
+	if(in_value){
+		value=in_value->Duplicate();
+		in_value->Copy(value);
+	}
+}
+/*}}}*/
+/*FUNCTION VectorParam::~VectorParam(){{{*/
+VectorParam::~VectorParam(){
+	delete value;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION VectorParam::Echo {{{*/
+void VectorParam::Echo(void){
+
+	_printf_("VectorParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+
+}
+/*}}}*/
+/*FUNCTION VectorParam::DeepEcho{{{*/
+void VectorParam::DeepEcho(void){
+
+	_printf_("VectorParam:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	value->Echo();
+}
+/*}}}*/
+/*FUNCTION VectorParam::Id{{{*/
+int    VectorParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION VectorParam::ObjectEnum{{{*/
+int VectorParam::ObjectEnum(void){
+
+	return VectorParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION VectorParam::copy{{{*/
+Object* VectorParam::copy() {
+
+	return new VectorParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*VectorParam virtual functions definitions: */
+/*FUNCTION VectorParam::GetParameterValue{{{*/
+void  VectorParam::GetParameterValue(Vector<IssmDouble>** poutput){
+	Vector<IssmDouble>*  output=NULL;
+
+	if(value){
+		output=value->Duplicate();
+		value->Copy(output);
+	}
+	*poutput=output;
+}
+/*}}}*/
+/*FUNCTION VectorParam::GetParameterName{{{*/
+void VectorParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION VectorParam::SetValue{{{*/
+void  VectorParam::SetValue(Vector<IssmDouble>* vector){
+
+	/*avoid leak: */
+	delete value;
+
+	/*copy: */
+	value=vector->Duplicate();
+	vector->Copy(value);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Params/VectorParam.h
===================================================================
--- /issm/trunk/src/c/classes/Params/VectorParam.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Params/VectorParam.h	(revision 15396)
@@ -0,0 +1,76 @@
+/*! \file VectorParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _VECTORPARAM_H_
+#define _VECTORPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class VectorParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		Vector<IssmDouble>* value;
+
+	public:
+		/*VectorParam constructors, destructors: {{{*/
+		VectorParam();
+		VectorParam(int enum_type,Vector<IssmDouble>* value);
+		~VectorParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(Vector<IssmDouble>** poutput);
+		void  GetParameterValue(FILE** pfid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
+
+		void  SetValue(bool boolean){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec);
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _VECTORPARAM_H */
Index: /issm/trunk/src/c/classes/Patch.cpp
===================================================================
--- /issm/trunk/src/c/classes/Patch.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/Patch.cpp	(revision 15396)
@@ -14,9 +14,5 @@
 #include <math.h>
 #include "./classes.h"
-#include "../Container/Container.h"
-#include "../io/io.h"
-#include "../EnumDefinitions/EnumDefinitions.h"
 #include "../shared/shared.h"
-#include "../include/include.h"
 
 /*Object constructors and destructors:*/
Index: /issm/trunk/src/c/classes/Profiler.cpp
===================================================================
--- /issm/trunk/src/c/classes/Profiler.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Profiler.cpp	(revision 15396)
@@ -0,0 +1,177 @@
+/*!\file Profiler.c
+ * \brief: implementation of the Profiler object
+ */
+
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Profiler.h"
+#include "./Params/Parameters.h"
+#include "./Params/DoubleParam.h"
+#include "../toolkits/toolkits.h"
+/*}}}*/
+
+/*Profiler constructors and destructors:*/
+/*FUNCTION Profiler::Profiler() default constructor {{{*/
+Profiler::Profiler(){
+		 this->time=new Parameters();
+		 this->flops=new Parameters();
+		 this->memory=new Parameters();
+}
+/*}}}*/
+/*FUNCTION Profiler::~Profiler(){{{*/
+Profiler::~Profiler(){
+	delete time;
+	delete flops;
+	delete memory;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Profiler::Echo{{{*/
+void Profiler::Echo(void){
+
+	_printf_("Profiler:\n");
+	_printf_("   time tags: \n");
+	this->time->Echo();
+
+}
+/*}}}*/
+/*FUNCTION Profiler::DeepEcho{{{*/
+void Profiler::DeepEcho(void){
+
+	_printf_("Profiler:\n");
+	_printf_("   time tags: \n");
+	this->time->DeepEcho();
+
+}
+/*}}}*/
+/*FUNCTION Profiler::Id{{{*/
+int    Profiler::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION Profiler::ObjectEnum{{{*/
+int Profiler::ObjectEnum(void){
+
+	return ProfilerEnum;
+
+}
+/*}}}*/
+
+/*Profiler routines:*/
+/*FUNCTION Profiler::Tag {{{*/
+void  Profiler::Tag(int tagenum,bool dontmpisync){
+
+	IssmDouble t;
+	IssmDouble f;
+	IssmDouble m;
+
+	/*If mpisync requested, make sure all the cpus are at the same point 
+	 *in the execution: */
+	if(!dontmpisync){
+		#ifdef _HAVE_MPI_
+		MPI_Barrier(IssmComm::GetComm()); 
+		#endif
+	}
+
+	/*Capture time: */
+	#ifdef _HAVE_MPI_
+	t=MPI_Wtime();
+	#else
+	t=(IssmPDouble)clock();
+	#endif
+
+	/*Capture flops: */
+	#ifdef _HAVE_PETSC_
+		PetscGetFlops(&f);
+		PetscMemoryGetCurrentUsage(&m);
+	#else
+		/*do nothing for now:*/
+	#endif
+
+	/*Plug into this->time: */
+	this->time->AddObject(new DoubleParam(tagenum,t));
+	this->flops->AddObject(new DoubleParam(tagenum,f));
+	this->memory->AddObject(new DoubleParam(tagenum,m));
+
+}
+/*}}}*/
+/*FUNCTION Profiler::DeltaTime {{{*/
+IssmDouble  Profiler::DeltaTime(int inittag, int finaltag){
+
+	IssmDouble init, final;
+	this->time->FindParam(&init,inittag);
+	this->time->FindParam(&final,finaltag);
+
+	#ifdef _HAVE_MPI_
+	return final-init;
+	#else
+	return (final-init)/CLOCKS_PER_SEC;
+	#endif
+}
+/*}}}*/
+/*FUNCTION Profiler::DeltaFlops {{{*/
+IssmDouble  Profiler::DeltaFlops(int inittag, int finaltag){
+
+	IssmDouble init, final;
+	this->flops->FindParam(&init,inittag);
+	this->flops->FindParam(&final,finaltag);
+
+	return final-init;
+}
+/*}}}*/
+/*FUNCTION Profiler::DeltaTimeModHour {{{*/
+int Profiler::DeltaTimeModHour(int inittag, int finishtag){
+
+	IssmDouble init, finish;
+	this->time->FindParam(&init,inittag);
+	this->time->FindParam(&finish,finishtag);
+
+	#ifdef _HAVE_MPI_
+	return int((reCast<int,IssmDouble>(finish-init))/3600);
+	#else
+	return int((reCast<int,IssmDouble>(finish-init))/CLOCKS_PER_SEC/3600);
+	#endif
+
+}
+/*}}}*/
+/*FUNCTION Profiler::DeltaTimeModMin {{{*/
+int Profiler::DeltaTimeModMin(int inittag, int finishtag){
+
+	IssmDouble init, finish;
+	this->time->FindParam(&init,inittag);
+	this->time->FindParam(&finish,finishtag);
+
+	#ifdef _HAVE_MPI_
+	return int(int(reCast<int,IssmDouble>(finish-init))%3600/60);
+	#else
+	return int(int(reCast<int,IssmDouble>(finish-init))/CLOCKS_PER_SEC%3600/60);
+	#endif
+}
+/*}}}*/
+/*FUNCTION Profiler::DeltaTimeModSec {{{*/
+int Profiler::DeltaTimeModSec(int inittag, int finishtag){
+
+	IssmDouble init, finish;
+	this->time->FindParam(&init,inittag);
+	this->time->FindParam(&finish,finishtag);
+
+	#ifdef _HAVE_MPI_
+	return int(reCast<int,IssmDouble>(finish-init))%60;
+	#else
+	return int(reCast<int,IssmDouble>(finish-init))/CLOCKS_PER_SEC%60;
+	#endif
+}
+/*}}}*/
+/*FUNCTION Profiler::Memory {{{*/
+IssmDouble  Profiler::Memory(int tag){
+
+	IssmDouble m;
+	this->memory->FindParam(&m,tag);
+
+	return m;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Profiler.h
===================================================================
--- /issm/trunk/src/c/classes/Profiler.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Profiler.h	(revision 15396)
@@ -0,0 +1,57 @@
+/*!\file Profiler.h
+ * \brief: header file for node object
+ */
+
+#ifndef _PROFILER_H_
+#define _PROFILER_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+class DataSet;
+class Parameters;
+
+enum ProfilerEnums {
+	Start,
+	StartInit,
+	FinishInit,
+	StartCore,
+	FinishCore,
+	StartAdCore,
+	FinishAdCore,
+	Finish
+};
+
+class Profiler: public Object{
+
+	public: 
+		Parameters*  time;
+		Parameters*  flops;
+		Parameters*  memory;
+
+		/*Profiler constructors, destructors {{{*/
+		Profiler();
+		~Profiler();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy()        {_error_("Not implemented yet"); };
+		/*}}}*/
+		/*Profiler routines {{{*/
+		void    Tag(int tagenum,bool dontmpisync=false);
+		IssmDouble  Memory(int tag);
+		IssmDouble  DeltaTime(int inittag, int finaltag);
+		IssmDouble  DeltaFlops(int inittag, int finaltag);
+		int     DeltaTimeModHour(int inittag, int finaltag);
+		int     DeltaTimeModMin(int inittag, int finaltag);
+		int     DeltaTimeModSec(int inittag, int finaltag);
+		/*}}}*/
+};
+
+#endif  /* _PROFILER_H_ */
Index: /issm/trunk/src/c/classes/RiftStruct.cpp
===================================================================
--- /issm/trunk/src/c/classes/RiftStruct.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/RiftStruct.cpp	(revision 15396)
@@ -4,7 +4,6 @@
 
 #include "./classes.h"
-#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/Enum/Enum.h"
 #include "../shared/shared.h"
-#include "../include/include.h"
 
 /*RiftStruct constructors and destructor*/
Index: /issm/trunk/src/c/classes/Segment.h
===================================================================
--- /issm/trunk/src/c/classes/Segment.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Segment.h	(revision 15396)
@@ -0,0 +1,84 @@
+/*!\file Segment.h
+ * \brief: header file for node object
+ */
+
+#ifndef _SEGMENT_H_
+#define _SEGMENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../datastructures/datastructures.h"
+#include "../shared/Numerics/constants.h"
+/*}}}*/
+
+template <class doubletype> 
+class Segment: public Object{
+
+	public:
+		int        eid;
+		doubletype x1;
+		doubletype y1;
+		doubletype x2;
+		doubletype y2;
+
+		/*Segment constructors, destructors :*/
+		/*FUNCTION Segment() default constructor {{{*/
+		Segment(){
+			this->eid = UNDEF;
+			this->x1  = UNDEF;
+			this->y1  = UNDEF;
+			this->x2  = UNDEF;
+			this->y2  = UNDEF;
+		}
+		/*}}}*/
+		/*FUNCTION Segment(int eid, doubletype x1,doubletype y1,doubletype x2, doubletype y2){{{*/
+		Segment(int segment_eid, doubletype segment_x1,doubletype segment_y1,doubletype segment_x2, doubletype segment_y2){
+
+			this->eid = segment_eid;
+			this->x1  = segment_x1;
+			this->y1  = segment_y1;
+			this->x2  = segment_x2;
+			this->y2  = segment_y2;
+
+		}
+		/*}}}*/
+		/*FUNCTION ~Segment(){{{*/
+		~Segment(){
+		}
+		/*}}}*/
+
+		/*Object virtual functions definitions:*/
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+
+			_printf_("Segment:\n");
+			_printf_("   eid: " << eid << "\n");
+			_printf_("   node 1: " << this->x1 << "|" << this->y1 << "\n");
+			_printf_("   node 2: " << this->x2 << "|" << this->y2 << "\n");
+
+		}
+		/*}}}*/
+		/*FUNCTION DeepEcho{{{*/
+		void DeepEcho(void){
+			this->Echo();
+		}
+		/*}}}*/
+		/*FUNCTION Id{{{*/
+		int    Id(void){ return eid; }
+		/*}}}*/
+		/*FUNCTION ObjectEnum{{{*/
+		int ObjectEnum(void){
+
+			return SegmentEnum;
+
+		}
+		/*}}}*/
+		/*FUNCTION copy {{{*/
+		Object* copy() {
+			return new Segment(this->eid,this->x1,this->y1,this->x2,this->y2);
+		}
+		/*}}}*/
+
+};
+
+#endif  /* _SEGMENT_H_ */
Index: /issm/trunk/src/c/classes/Vertex.cpp
===================================================================
--- /issm/trunk/src/c/classes/Vertex.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Vertex.cpp	(revision 15396)
@@ -0,0 +1,254 @@
+/*!\file Vertex.c
+ * \brief: implementation of the Vertex object
+ */
+
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <string.h>
+#include "classes.h"
+#include "shared/shared.h"
+/*}}}*/
+
+/*Vertex constructors and destructor:*/
+/*FUNCTION Vertex::Vertex() {{{*/
+Vertex::Vertex(){
+	return;
+}
+/*}}}*/
+/*FUNCTION Vertex::Vertex(int vertex_id, IssmDouble vertex_x, IssmDouble vertex_y, IssmDouble vertex_z, IssmDouble vertex_sigma){{{*/
+Vertex::Vertex(int vertex_id, int vertex_sid,IssmDouble vertex_x, IssmDouble vertex_y, IssmDouble vertex_z, IssmDouble vertex_sigma,int vertex_connectivity){
+	this->Init(vertex_id, vertex_sid,vertex_x, vertex_y, vertex_z, vertex_sigma,vertex_connectivity);
+}
+/*}}}*/
+/*FUNCTION Vertex::Vertex(int vertex_id, int vertex_sid,int i, IoModel* iomodel) {{{*/
+Vertex::Vertex(int vertex_id, int vertex_sid,int i, IoModel* iomodel){
+
+	_assert_(iomodel->Data(MeshXEnum) && iomodel->Data(MeshYEnum) && iomodel->Data(MeshZEnum));
+	_assert_(iomodel->Data(BedEnum) && iomodel->Data(ThicknessEnum) && iomodel->numbernodetoelementconnectivity);
+
+	this->Init(vertex_id, vertex_sid, iomodel->Data(MeshXEnum)[i],iomodel->Data(MeshYEnum)[i],iomodel->Data(MeshZEnum)[i],(iomodel->Data(MeshZEnum)[i]-iomodel->Data(BedEnum)[i])/(iomodel->Data(ThicknessEnum)[i]),iomodel->numbernodetoelementconnectivity[i]);
+
+}
+/*}}}*/
+/*FUNCTION Vertex::~Vertex() {{{*/
+Vertex::~Vertex(){
+	return;
+}
+/*}}}*/
+/*FUNCTION Vertex::Init{{{*/
+void Vertex::Init(int vertex_id, int vertex_sid,IssmDouble vertex_x, IssmDouble vertex_y, IssmDouble vertex_z, IssmDouble vertex_sigma,int vertex_connectivity){
+
+	/*all the initialization has been done by the initializer, just fill in the id: */
+	this->id=vertex_id;
+	this->sid=vertex_sid;
+	this->pid=UNDEF;
+	this->x=vertex_x;
+	this->y=vertex_y;
+	this->z=vertex_z;
+	this->sigma=vertex_sigma;
+	this->connectivity=vertex_connectivity;
+
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Vertex::Echo{{{*/
+void Vertex::Echo(void){
+
+	_printf_("Vertex:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   pid: " << pid << "\n");
+	_printf_("   x: " << x << "\n");
+	_printf_("   y: " << y << "\n");
+	_printf_("   z: " << z << "\n");
+	_printf_("   sigma: " << sigma << "\n");
+	_printf_("   connectivity: " << connectivity << "\n");
+	_printf_("   clone: " << clone << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Vertex::DeepEcho{{{*/
+void Vertex::DeepEcho(void){
+	this->Echo();
+}
+/*}}}*/
+/*FUNCTION Vertex::Id{{{*/
+int    Vertex::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Vertex::ObjectEnum{{{*/
+int Vertex::ObjectEnum(void){
+
+	return VertexEnum;
+
+}
+/*}}}*/
+/*FUNCTION Vertex::copy {{{*/
+Object* Vertex::copy() {
+
+	return new Vertex(*this); 
+
+}
+/*}}}*/
+
+/*Vertex management: */
+/*FUNCTION Vertex::Connectivity{{{*/
+int    Vertex::Connectivity(void){return connectivity;}
+/*}}}*/
+/*FUNCTION Vertex::GetX {{{*/
+IssmDouble Vertex::GetX(){
+	return this->x;
+}
+/*}}}*/
+/*FUNCTION Vertex::GetY {{{*/
+IssmDouble Vertex::GetY(){
+	return this->y;
+}
+/*}}}*/
+/*FUNCTION Vertex::GetZ {{{*/
+IssmDouble Vertex::GetZ(){
+	return this->z;
+}
+/*}}}*/
+/*FUNCTION Vertex::Sid{{{*/
+int    Vertex::Sid(void){ return sid; }
+/*}}}*/
+/*FUNCTION Vertex::Pid{{{*/
+int    Vertex::Pid(void){ return pid; }
+/*}}}*/
+/*FUNCTION Vertex::UpdatePosition {{{*/
+void  Vertex::UpdatePosition(Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed){
+
+	IssmDouble oldz,newz;
+	IssmDouble dt,velz;
+
+	/*Get time stepping*/
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+
+	/*sigma remains constant. z=bed+sigma*thickness*/
+	oldz = this->z;
+	newz = bed[this->pid]+sigma*thickness[this->pid];
+	velz = (newz-oldz)/dt;
+	this->z = newz;
+
+	/*put vz in vector*/
+	vz->SetValue(this->pid,velz,INS_VAL);
+}
+/*}}}*/
+/*FUNCTION Vertex::DistributePids{{{*/
+void  Vertex::DistributePids(int* ppidcount){
+
+	/*retrieve current pid*/
+	int pidcount=*ppidcount;
+
+	/*This vertex is a clone! Don't distribute pids, it will get them from another cpu!*/
+	if(this->clone) return;
+
+	/*This vertex should distribute its pid*/
+	this->pid=pidcount;
+	pidcount++;
+
+	/*Assign output pointers: */
+	*ppidcount=pidcount;
+}
+/*}}}*/
+/*FUNCTION Vertex::OffsetPids{{{*/
+void  Vertex::OffsetPids(int pidcount){
+
+	/*This vertex is a clone, don't offset the pids*/
+	if(this->clone) return;
+
+	/*This vertex should offset his pid, go ahead: */
+	this->pid+=pidcount;
+}
+/*}}}*/
+/*FUNCTION Vertex::ShowTruePids{{{*/
+void  Vertex::ShowTruePids(int* truepids){
+
+	/*Are we a clone? : */
+	if(this->clone)return;
+
+	/*Ok, we are not a clone, just plug our pid into truepids: */
+	truepids[this->sid]=this->pid;
+}
+/*}}}*/
+/*FUNCTION Vertex::UpdateClonePids{{{*/
+void  Vertex::UpdateClonePids(int* alltruepids){
+
+	/*If we are not a clone, don't update, we already have pids: */
+	if(!this->clone)return;
+
+	/*Ok, we are a clone node, but we did not create the pid for this vertex 
+	 * Therefore, our pid is garbage right now. Go pick it up in the alltruepids: */
+	this->pid=alltruepids[this->sid];
+}
+/*}}}*/
+/*FUNCTION Vertex::SetClone {{{*/
+void  Vertex::SetClone(int* minranks){
+
+	int my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if (minranks[this->sid]==my_rank){
+		this->clone=false;
+	}
+	else{
+		/*!there is a cpu with lower rank that has the same vertex, 
+		therefore, I am a clone*/
+		this->clone=true;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Vertex::ToXYZ {{{*/
+void  Vertex::ToXYZ(Matrix<IssmDouble>* matrix){
+
+	IssmDouble xyz[3];
+	int        indices[3];
+
+	if (this->clone==true) return;
+
+	xyz[0]=x;
+	xyz[1]=y; 
+	xyz[2]=z;
+	indices[0]=0;
+	indices[1]=1; 
+	indices[2]=2;
+
+	matrix->SetValues(1,&sid,3,&indices[0],&xyz[0],INS_VAL);
+}
+/*}}}*/
+/*FUNCTION Vertex::VertexCoordinates {{{*/
+void  Vertex::VertexCoordinates(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz){
+
+	if (this->clone==true) return;
+
+	vx->SetValue(this->sid,this->x,INS_VAL);
+	vy->SetValue(this->sid,this->y,INS_VAL);
+	vz->SetValue(this->sid,this->z,INS_VAL);
+
+	return;
+}
+/*}}}*/
+
+/*Methods relating to Vertex, but not internal methods: */
+void GetVerticesCoordinates(IssmDouble* xyz,Vertex** vertices, int numvertices){ /*{{{*/
+
+	_assert_(vertices);
+	_assert_(xyz);
+
+	for(int i=0;i<numvertices;i++) {
+		xyz[i*3+0]=vertices[i]->GetX();
+		xyz[i*3+1]=vertices[i]->GetY();
+		xyz[i*3+2]=vertices[i]->GetZ();
+	}
+}/*}}}*/
Index: /issm/trunk/src/c/classes/Vertex.h
===================================================================
--- /issm/trunk/src/c/classes/Vertex.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Vertex.h	(revision 15396)
@@ -0,0 +1,66 @@
+/*! \file Vertex.h 
+ *  \brief: header file for vertex object
+ */
+
+#ifndef _VERTEX_H_
+#define _VERTEX_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./classes.h"
+#include "../shared/Exceptions/exceptions.h"
+#include "../toolkits/toolkits.h"
+template <class doubletype> class Vector;
+template <class doubletype> class Matrix;
+class Parameters;
+class IoModel;
+/*}}}*/
+
+class Vertex: public Object{
+
+	public: 
+		bool       clone;
+		int        id;           // random index
+		int        sid;          // "serial" id (rank of this vertex if the dataset was on 1 cpu)
+		int        pid;          // "parallel" id
+		IssmDouble x;
+		IssmDouble y;
+		IssmDouble z;
+		IssmDouble sigma;        //sigma coordinate: (z-bed)/thickness
+		int        connectivity; //number of vertices connected to this vertex
+
+		/*Vertex constructors, destructors {{{*/
+		Vertex();
+		Vertex(int id, int sid,IssmDouble x, IssmDouble y, IssmDouble z, IssmDouble sigma, int connectivity); 
+		void Init(int id, int sid, IssmDouble x, IssmDouble y, IssmDouble z, IssmDouble sigma,int connectivity);
+		Vertex(int id, int sid, int i, IoModel* iomodel);
+		~Vertex();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Vertex management:*/ 
+		int        Pid(void); 
+		int        Sid(void); 
+		int        Connectivity(void); 
+		IssmDouble GetX(void); 
+		IssmDouble GetY(void); 
+		IssmDouble GetZ(void); 
+		void       UpdatePosition(Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed);
+		void       DistributePids(int* ppidcount);
+		void       OffsetPids(int pidcount);
+		void       ShowTruePids(int* borderpids);
+		void       UpdateClonePids(int* allborderpids);
+		void       SetClone(int* minranks);
+		void       ToXYZ(Matrix<IssmDouble>* matrix);
+		void       VertexCoordinates(Vector<IssmDouble>* vx,Vector<IssmDouble>* vy,Vector<IssmDouble>* vz);
+};
+
+/*Methods relating to Vertex object: */
+void GetVerticesCoordinates(IssmDouble* xyz,Vertex** vertices, int numvertices);
+
+#endif  /* _VERTEX_H */
Index: /issm/trunk/src/c/classes/Vertices.cpp
===================================================================
--- /issm/trunk/src/c/classes/Vertices.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/Vertices.cpp	(revision 15396)
@@ -0,0 +1,242 @@
+/*
+ * \file Vertices.cpp
+ * \brief: Implementation of Vertices class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <vector>
+#include <functional>
+#include <algorithm>
+#include <iostream>
+
+#include "./Vertices.h"
+#include "../shared/shared.h"
+#include "./Vertex.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Vertices::Vertices(){{{*/
+Vertices::Vertices(){
+	enum_type=VerticesEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Vertices::~Vertices(){{{*/
+Vertices::~Vertices(){
+	return;
+}
+/*}}}*/
+
+/*Numerics management*/
+/*FUNCTION Vertices::DistributePids{{{*/
+void  Vertices::DistributePids(int numberofobjects){
+
+	int num_procs;
+	int my_rank;
+
+	int  i;
+	int  pidcount    = 0;
+	int *allpidcount = NULL;
+	int *truepids    = NULL;
+	int *alltruepids = NULL;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
+
+	/*Go through objects, and distribute pids locally, from 0 to numberofpidsperobject*/
+	for (i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->DistributePids(&pidcount);
+	}
+
+	/* Now every object has distributed pids, but locally, and with a pid count starting from 
+	 * 0. This means the pids between all the cpus are not unique. We now offset the pids of each
+	 * cpus by the total last pids of the previus cpu, starting from 0.
+	 * 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
+
+	/* Every cpu should start its own pid count at the end of the pidcount from cpu-1*/
+	pidcount=0;
+	if(my_rank!=0){
+		for(i=0;i<my_rank;i++){
+			pidcount+=allpidcount[i];
+		}
+	}
+	for (i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->OffsetPids(pidcount);
+	}
+
+	/* Finally, remember that cpus may have skipped some objects, because they were clones. For every 
+	 * object that is not a clone, tell them to show their pids, so that later on, they can get picked 
+	 * up by their clones: */
+	truepids   =xNewZeroInit<int>(numberofobjects);
+	alltruepids=xNewZeroInit<int>(numberofobjects);
+	for (i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		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
+
+	/* Now every cpu knows the true pids of everyone else that is not a clone*/
+	for(i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->UpdateClonePids(alltruepids);
+	}
+
+	/* Free ressources: */
+	xDelete<int>(allpidcount);
+	xDelete<int>(truepids);
+	xDelete<int>(alltruepids);
+}
+/*}}}*/
+/*FUNCTION Vertices::FlagClones{{{*/
+void  Vertices::FlagClones(int numberofobjects){
+
+	int i;
+	int num_procs;
+
+	int* ranks=NULL;
+	int* minranks=NULL;
+
+	/*recover num_procs:*/
+	num_procs=IssmComm::GetSize();
+
+	/*Allocate ranks: */
+	ranks=xNew<int>(numberofobjects);
+	minranks=xNew<int>(numberofobjects);
+
+	for(i=0;i<numberofobjects;i++)ranks[i]=num_procs; //no cpu can have rank num_procs. This is the maximum limit.
+
+	/*Now go through all our objects and ask them to report to who they belong (which rank): */
+	Ranks(ranks);
+
+	/*We need to take the minimum rank for each vertex, and every cpu needs to get that result. That way, 
+	 * when we start building the dof list for all vertexs, a cpu can check whether its vertex already has been 
+	 * 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
+
+	/*Now go through all objects, and use minranks to flag which objects are cloned: */
+	for(i=0;i<this->Size();i++){
+		/*For this object, decide whether it is a clone: */
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->SetClone(minranks);
+	}
+
+	/*Free ressources: */
+	xDelete<int>(ranks); 
+	xDelete<int>(minranks);
+
+}
+/*}}}*/
+/*FUNCTION Vertices::NumberOfVertices{{{*/
+int Vertices::NumberOfVertices(void){
+
+	int i,sid;
+	int max_sid=0;
+	int vertex_max_sid;
+
+	for(i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		sid=vertex->Sid();
+		if (sid>max_sid)max_sid=sid;
+	}
+
+	#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());
+	max_sid=vertex_max_sid;
+	#endif
+
+	/*sid starts at 0*/
+	max_sid++;
+
+	/*return:*/
+	return max_sid;
+}
+/*}}}*/
+/*FUNCTION Vertices::Ranks{{{*/
+void   Vertices::Ranks(int* ranks){
+
+	int my_rank;
+	int        sid;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*Go through a dataset, and for each object, report it cpu: */
+	for(int i=0;i<this->Size();i++){
+		/*Plug rank into ranks, according to id: */
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		sid=vertex->Sid();
+		ranks[sid]=my_rank; 
+	}
+}
+/*}}}*/
+/*FUNCTION Vertices::ToXYZ{{{*/
+IssmDouble* Vertices::ToXYZ(void){
+
+	/*intermediary: */
+	int i;
+	int my_rank;
+	int num_vertices;
+
+	/*output: */
+	Matrix<IssmDouble>* xyz = NULL;
+	IssmDouble* xyz_serial=NULL;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*First, figure out number of vertices: */
+	num_vertices=this->NumberOfVertices();
+
+	/*Now, allocate matrix to hold all the vertices x,y and z values: */
+	xyz= new Matrix<IssmDouble>(num_vertices,3);
+
+	/*Go through vertices, and for each vertex, object, report it cpu: */
+	for(i=0;i<this->Size();i++){
+
+		/*let vertex fill matrix: */
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->ToXYZ(xyz);
+	}
+
+	/*Assemble:*/
+	xyz->Assemble();
+
+	/*gather on cpu 0: */
+	xyz_serial=xyz->ToSerial();
+
+	/*free ressources: */
+	delete xyz;
+	if(my_rank!=0)delete xyz_serial;
+
+	/*return matrix: */
+	return xyz_serial;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Vertices.h
===================================================================
--- /issm/trunk/src/c/classes/Vertices.h	(revision 15396)
+++ /issm/trunk/src/c/classes/Vertices.h	(revision 15396)
@@ -0,0 +1,30 @@
+#ifndef _CONTAINER_VERTICES_H_
+#define  _CONTAINER_VERTICES_H_
+
+/*forward declarations */
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+
+/*!\brief Declaration of Vertices class.
+ *
+ * Declaration of Vertices class.  Vertices are vector lists (Containers) of Vertex objects.
+ * A vertex is a set of (x,y,z) coordinates defining the location of points in the mesh (not
+ * to be confused with a node, which is a degree of freedom (DOF) for a particular analysis).
+ */ 
+class Vertices: public DataSet{
+
+	public:
+
+		/*constructors, destructors:*/ 
+		Vertices();
+		~Vertices();
+
+		/*numerics:*/
+		void  DistributePids(int numberofnodes);
+		void  FlagClones(int numberofnodes);
+		int   NumberOfVertices(void);
+		void  Ranks(int* ranks);
+		IssmDouble* ToXYZ(void);
+};
+
+#endif //ifndef _VERTICES_H_
Index: /issm/trunk/src/c/classes/classes.h
===================================================================
--- /issm/trunk/src/c/classes/classes.h	(revision 15395)
+++ /issm/trunk/src/c/classes/classes.h	(revision 15396)
@@ -3,15 +3,105 @@
  */
 
-#ifndef ALL_CLASSES_H_
-#define ALL_CLASSES_H_
+#ifndef _ALL_CLASSES_H_
+#define _ALL_CLASSES_H_
 
-/*Objects derived classes, which are used in our containers: */
-#include "./objects/objects.h"
+/*Objects: */
+#include "./Contour.h"
+#include "./Vertices.h"
+#include "./Vertex.h"
+#include "./Nodes.h"
+#include "./Contours.h"
+#include "./Node.h"
+#include "./Profiler.h"
+#include "./DependentObject.h"
+#include "./IndependentObject.h"
+#include "./Segment.h"
+
+/*Constraints: */
+#include "./Constraints/Constraints.h"
+#include "./Constraints/Constraint.h"
+#include "./Constraints/SpcStatic.h"
+#include "./Constraints/SpcTransient.h"
+#include "./Constraints/SpcDynamic.h"
+
+/*Loads: */
+#include "./Loads/Loads.h"
+#include "./Loads/Load.h"
+#include "./Loads/Friction.h"
+#include "./Loads/Icefront.h"
+#include "./Loads/Numericalflux.h"
+#include "./Loads/Riftfront.h"
+#include "./Loads/Penpair.h"
+#include "./Loads/Pengrid.h"
+
+/*Elements: */
+#include "./Elements/Elements.h"
+#include "./Elements/Element.h"
+#include "./Elements/Penta.h"
+#include "./Elements/PentaRef.h"
+#include "./Elements/Tria.h"
+#include "./Elements/TriaRef.h"
+#include "./Elements/ElementHook.h"
+
+/*Option parsing objects: */
+#include "./Options/Option.h"
+#include "./Options/Options.h"
+#include "./Options/GenericOption.h"
+#include "./Options/OptionUtilities.h"
+
+/*Inputs: */
+#include "./Inputs/Inputs.h"
+#include "./Inputs/Input.h"
+#include "./Inputs/BoolInput.h"
+#include "./Inputs/DoubleInput.h"
+#include "./Inputs/IntInput.h"
+#include "./Inputs/PentaP1Input.h"
+#include "./Inputs/TriaInput.h"
+#include "./Inputs/ControlInput.h"
+#include "./Inputs/DatasetInput.h"
+#include "./Inputs/TransientInput.h"
+
+/*ElementResults: */
+#include "./ElementResults/ElementResult.h"
+#include "./ElementResults/DoubleElementResult.h"
+#include "./ElementResults/TriaP1ElementResult.h"
+#include "./ElementResults/PentaP1ElementResult.h" 
+#include "./ElementResults/BoolElementResult.h"
+
+/*ExternalResults: */
+#include "./ExternalResults/Results.h"
+#include "./ExternalResults/ExternalResult.h"
+#include "./ExternalResults/GenericExternalResult.h"
+
+/*Materials: */
+#include "./Materials/Materials.h"
+#include "./Materials/Material.h"
+#include "./Materials/Matice.h"
+#include "./Materials/Matdamageice.h"
+#include "./Materials/Matpar.h"
+
+/*Params: */
+#include "./Params/GenericParam.h"
+#include "./Params/BoolParam.h"
+#include "./Params/DoubleMatParam.h"
+#include "./Params/DoubleTransientMatParam.h"
+#include "./Params/DoubleMatArrayParam.h"
+#include "./Params/DoubleParam.h"
+#include "./Params/DoubleVecParam.h"
+#include "./Params/IntParam.h"
+#include "./Params/IntVecParam.h"
+#include "./Params/IntMatParam.h"
+#include "./Params/FileParam.h"
+#include "./Params/Parameters.h"
+#include "./Params/Param.h"
+#include "./Params/MatrixParam.h"
+#include "./Params/VectorParam.h"
+#include "./Params/StringArrayParam.h"
+#include "./Params/StringParam.h"
+#include "./Params/TransientParam.h"
+#include "./Params/DataSetParam.h"
 
 /*matrix: */
 #include "./matrix/matrixobjects.h"
-
-/*bamg: */
-#include "./bamg/bamgobjects.h"
 
 /*gauss: */
@@ -28,8 +118,5 @@
 #include "./Update.h"
 #include "./FemModel.h"
-#include "./OptArgs.h"
-#include "./OptPars.h"
-#include "./AdolcEdf.h"
-#include "./IssmComm.h"
+#include "./GiaDeflectionCoreArgs.h"
 #include "./RiftStruct.h"
 
Index: /issm/trunk/src/c/classes/gauss/GaussPenta.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 15396)
@@ -3,5 +3,11 @@
  */
 
-#include "./gaussobjects.h"
+#include "./GaussPenta.h"
+#include "./GaussTria.h"
+#include "../../shared/io/Print/Print.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Numerics/GaussPoints.h"
+#include "../../shared/Numerics/constants.h"
 
 /*GaussPenta constructors and destructors:*/
@@ -31,8 +37,8 @@
 	int     numgauss_horiz;
 	int     numgauss_vert;
-	double *coords1_horiz = NULL;
-	double *coords2_horiz = NULL;
-	double *coords3_horiz = NULL;
-	double *weights_horiz  = NULL;
+	IssmDouble *coords1_horiz = NULL;
+	IssmDouble *coords2_horiz = NULL;
+	IssmDouble *coords3_horiz = NULL;
+	IssmDouble *weights_horiz  = NULL;
 	double *coords_vert = NULL;
 	double *weights_vert   = NULL;
@@ -45,9 +51,9 @@
 	/*Allocate GaussPenta fields*/
 	numgauss=numgauss_horiz*numgauss_vert;
-	coords1=xNew<double>(numgauss);
-	coords2=xNew<double>(numgauss);
-	coords3=xNew<double>(numgauss);
-	coords4=xNew<double>(numgauss);
-	weights=xNew<double>(numgauss);
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	coords4=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
 
 	/*Combine Horizontal and vertical points*/
@@ -70,9 +76,9 @@
 
 	/*Clean up*/
-	xDelete<double>(coords1_horiz);
-	xDelete<double>(coords2_horiz);
-	xDelete<double>(coords3_horiz);
+	xDelete<IssmDouble>(coords1_horiz);
+	xDelete<IssmDouble>(coords2_horiz);
+	xDelete<IssmDouble>(coords3_horiz);
 	xDelete<double>(coords_vert);
-	xDelete<double>(weights_horiz);
+	xDelete<IssmDouble>(weights_horiz);
 	xDelete<double>(weights_vert);
 }
@@ -91,9 +97,9 @@
 
 	/*Allocate GaussPenta fields*/
-	coords1=xNew<double>(numgauss);
-	coords2=xNew<double>(numgauss);
-	coords3=xNew<double>(numgauss);
-	coords4=xNew<double>(numgauss);
-	weights=xNew<double>(numgauss);
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	coords4=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
 
 	if(index1==0 && index2==3){
@@ -145,5 +151,5 @@
 
 		/*compute z coordinate*/
-		coords4=xNew<double>(numgauss);
+		coords4=xNew<IssmDouble>(numgauss);
 		for(int i=0;i<numgauss;i++) coords4[i]=-1.0;
 	}
@@ -155,5 +161,5 @@
 
 		/*compute z coordinate*/
-		coords4=xNew<double>(numgauss);
+		coords4=xNew<IssmDouble>(numgauss);
 		for(int i=0;i<numgauss;i++) coords4[i]=1.0;
 	}
@@ -180,9 +186,9 @@
 	/*Allocate GaussPenta fields*/
 	numgauss=order_horiz*order_vert;
-	coords1=xNew<double>(numgauss);
-	coords2=xNew<double>(numgauss);
-	coords3=xNew<double>(numgauss);
-	coords4=xNew<double>(numgauss);
-	weights=xNew<double>(numgauss);
+	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  */
@@ -233,9 +239,9 @@
 /*FUNCTION GaussPenta::~GaussPenta(){{{*/
 GaussPenta::~GaussPenta(){
-	xDelete<double>(weights);
-	xDelete<double>(coords1);
-	xDelete<double>(coords2);
-	xDelete<double>(coords3);
-	xDelete<double>(coords4);
+	xDelete<IssmDouble>(weights);
+	xDelete<IssmDouble>(coords1);
+	xDelete<IssmDouble>(coords2);
+	xDelete<IssmDouble>(coords3);
+	xDelete<IssmDouble>(coords4);
 }
 /*}}}*/
@@ -245,43 +251,43 @@
 void GaussPenta::Echo(void){
 
-	_printLine_("GaussPenta:");
-	_printLine_("   numgauss: " << numgauss);
+	_printf_("GaussPenta:\n");
+	_printf_("   numgauss: " << numgauss << "\n");
 
 	if (weights){
-	 _printString_("   weights = ["); 
-	 for(int i=0;i<numgauss;i++) _printLine_(" " << weights[i]);
-	 _printLine_("]");
-	}
-	else _printLine_("weights = NULL");
+	 _printf_("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << weights[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("weights = NULL\n");
 	if (coords1){
-	 _printString_("   coords1 = ["); 
-	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords1[i]);
-	 _printLine_("]");
-	}
-	else _printLine_("coords1 = NULL");
+	 _printf_("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords1[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords1 = NULL\n");
 	if (coords2){
-	 _printString_("   coords2 = ["); 
-	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords2[i]);
-	 _printLine_("]");
-	}
-	else _printLine_("coords2 = NULL");
+	 _printf_("   coords2 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords2[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords2 = NULL\n");
 	if (coords3){
-	 _printString_("   coords3 = ["); 
-	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords3[i]);
-	 _printLine_("]");
-	}
-	else _printLine_("coords3 = NULL");
+	 _printf_("   coords3 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords3[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords3 = NULL\n");
 	if (coords4){
-		_printString_("   coords4 = ["); 
-		for(int i=0;i<numgauss;i++) _printLine_(" " << coords4[i]);
-		_printLine_("]");
-	}
-	else _printLine_("coords4 = NULL");
-
-	_printLine_("   weight = " << weight);
-	_printLine_("   coord1 = " << coord1);
-	_printLine_("   coord2 = " << coord2);
-	_printLine_("   coord3 = " << coord3);
-	_printLine_("   coord4 = " << coord4);
+		_printf_("   coords4 = ["); 
+		for(int i=0;i<numgauss;i++) _printf_(" " << coords4[i] << "\n");
+		_printf_("]\n");
+	}
+	else _printf_("coords4 = NULL\n");
+
+	_printf_("   weight = " << weight << "\n");
+	_printf_("   coord1 = " << coord1 << "\n");
+	_printf_("   coord2 = " << coord2 << "\n");
+	_printf_("   coord3 = " << coord3 << "\n");
+	_printf_("   coord4 = " << coord4 << "\n");
 
 }
@@ -355,5 +361,5 @@
 	if(index1==0 && index2==1 && index3==2){
 		GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
-		coords4=xNew<double>(numgauss);
+		coords4=xNew<IssmDouble>(numgauss);
 		for(int i=0;i<numgauss;i++) coords4[i]=-1.0;
 	}
Index: /issm/trunk/src/c/classes/gauss/GaussPenta.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.h	(revision 15395)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.h	(revision 15396)
@@ -7,8 +7,6 @@
 
 /*Headers:*/
-/*{{{*/
-#include "./../../shared/shared.h"
+#include "../../shared/Numerics/types.h"
 class GaussTria;
-/*}}}*/
 
 class GaussPenta{
@@ -16,16 +14,16 @@
 	private:
 		int numgauss;
-		double* weights;
-		double* coords1;
-		double* coords2;
-		double* coords3;
-		double* coords4;
+		IssmDouble* weights;
+		IssmDouble* coords1;
+		IssmDouble* coords2;
+		IssmDouble* coords3;
+		IssmDouble* coords4;
 
 	public:
-		double weight;
-		double coord1;
-		double coord2;
-		double coord3;
-		double coord4;
+		IssmDouble weight;
+		IssmDouble coord1;
+		IssmDouble coord2;
+		IssmDouble coord3;
+		IssmDouble coord4;
 
 	public:
Index: /issm/trunk/src/c/classes/gauss/GaussTria.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 15396)
@@ -3,5 +3,6 @@
  */
 
-#include "./gaussobjects.h"
+#include "./GaussTria.h"
+#include "../../shared/shared.h"
 
 /*GaussTria constructors and destructors:*/
@@ -42,4 +43,5 @@
 	IssmPDouble *seg_coords  = NULL;
 	IssmPDouble *seg_weights = NULL;
+	IssmDouble  a1,b1,c1,a2,b2,c2;
 	int     i,index3;
 
@@ -49,36 +51,42 @@
 
 	/*Allocate GaussTria fields*/
-	coords1=xNew<IssmPDouble>(numgauss);
-	coords2=xNew<IssmPDouble>(numgauss);
-	coords3=xNew<IssmPDouble>(numgauss);
-	weights=xNew<IssmPDouble>(numgauss);
-
-	/*Reverse index1 and 2 if necessary*/
-	if (index1>index2){
-		index3=index1; index1=index2; index2=index3;
-		for(i=0;i<numgauss;i++) seg_coords[i]=-seg_coords[i];
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
+
+	/*Figure out coords of index1 (a1,b1,c1) and index2 (a2,b2,c2)*/
+	if(index1==0){
+		a1=1; b1=0; c1=0;
+	}
+	else if(index1==1){
+		a1=0; b1=1; c1=0;
+	}
+	else if(index1==2){
+		a1=0; b1=0; c1=1;
+	}
+	else{
+		_error_("First indice provided is not supported yet (user provided " << index1 << ")");
+	}
+	if(index2==0){
+		a2=1; b2=0; c2=0;
+	}
+	else if(index2==1){
+		a2=0; b2=1; c2=0;
+	}
+	else if(index2==2){
+		a2=0; b2=0; c2=1;
+	}
+	else{
+	 _error_("Second indice provided is not supported yet (user provided " << index2 << " )");
 	}
 
 	/*Build Triangle Gauss point*/
-	if (index1==0 && index2==1){
-		for(i=0;i<numgauss;i++) coords1[i]=  0.5*(1-seg_coords[i]);
-		for(i=0;i<numgauss;i++) coords2[i]=1-0.5*(1.-seg_coords[i]);
-		for(i=0;i<numgauss;i++) coords3[i]=0;
-		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
-	}
-	else if (index1==0 && index2==2){
-		for(i=0;i<numgauss;i++) coords1[i]=  0.5*(1-seg_coords[i]);
-		for(i=0;i<numgauss;i++) coords2[i]= 0 ;
-		for(i=0;i<numgauss;i++) coords3[i]=1-0.5*(1.-seg_coords[i]);
-		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
-	}
-	else if (index1==1 && index2==2){
-		for(i=0;i<numgauss;i++) coords1[i]=0;
-		for(i=0;i<numgauss;i++) coords2[i]=  0.5*(1-seg_coords[i]);
-		for(i=0;i<numgauss;i++) coords3[i]=1-0.5*(1.-seg_coords[i]);
-		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
-	}
-	else
-	 _error_("The 2 indices provided are not supported yet (user provided " << index1 << " and " << index2 << ")");
+	for(i=0;i<numgauss;i++){
+		coords1[i]=0.5*(a1+a2) + 0.5*seg_coords[i]*(a2-a1);
+		coords2[i]=0.5*(b1+b2) + 0.5*seg_coords[i]*(b2-b1);
+		coords3[i]=0.5*(c1+c2) + 0.5*seg_coords[i]*(c2-c1);
+		weights[i]=seg_weights[i];
+	}
 
 	/*Initialize static fields as undefined*/
@@ -93,10 +101,166 @@
 }
 /*}}}*/
+/*FUNCTION GaussTria::GaussTria(int index,double r1,double r2,int order) {{{*/
+GaussTria::GaussTria(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;
+		}
+	}
+	else{
+		/*Double number of gauss points*/
+		GaussTria *gauss1    = NULL;
+		GaussTria *gauss2    = NULL;
+		gauss1=new GaussTria(order);
+		gauss2=new GaussTria(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->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->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->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;
+}
+/*}}}*/
 /*FUNCTION GaussTria::~GaussTria(){{{*/
 GaussTria::~GaussTria(){
-	xDelete<IssmPDouble>(weights);
-	xDelete<IssmPDouble>(coords1);
-	xDelete<IssmPDouble>(coords2);
-	xDelete<IssmPDouble>(coords3);
+	xDelete<IssmDouble>(weights);
+	xDelete<IssmDouble>(coords1);
+	xDelete<IssmDouble>(coords2);
+	xDelete<IssmDouble>(coords3);
 }
 /*}}}*/
@@ -106,36 +270,36 @@
 void GaussTria::Echo(void){
 
-	_printLine_("GaussTria:");
-	_printLine_("   numgauss: " << numgauss);
+	_printf_("GaussTria:\n");
+	_printf_("   numgauss: " << numgauss << "\n");
 
 	if (weights){
-	 _printString_("   weights = ["); 
-	 for(int i=0;i<numgauss;i++) _printLine_(" " << weights[i]);
-	 _printLine_("]");
-	}
-	else _printLine_("weights = NULL");
+	 _printf_("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << weights[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("weights = NULL\n");
 	if (coords1){
-	 _printString_("   coords1 = ["); 
-	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords1[i]);
-	 _printLine_("]");
-	}
-	else _printLine_("coords1 = NULL");
+	 _printf_("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords1[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords1 = NULL\n");
 	if (coords2){
-	 _printString_("   coords2 = ["); 
-	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords2[i]);
-	 _printLine_("]");
-	}
-	else _printLine_("coords2 = NULL");
+	 _printf_("   coords2 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords2[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords2 = NULL\n");
 	if (coords3){
-	 _printString_("   coords3 = ["); 
-	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords3[i]);
-	 _printLine_("]");
-	}
-	else _printLine_("coords3 = NULL");
-
-	_printLine_("   weight = " << weight);
-	_printLine_("   coord1 = " << coord1);
-	_printLine_("   coord2 = " << coord2);
-	_printLine_("   coord3 = " << coord3);
+	 _printf_("   coords3 = ["); 
+	 for(int i=0;i<numgauss;i++) _printf_(" " << coords3[i] << "\n");
+	 _printf_("]\n");
+	}
+	else _printf_("coords3 = NULL\n");
+
+	_printf_("   weight = " << weight << "\n");
+	_printf_("   coord1 = " << coord1 << "\n");
+	_printf_("   coord2 = " << coord2 << "\n");
+	_printf_("   coord3 = " << coord3 << "\n");
 
 }
@@ -231,16 +395,40 @@
 	/*update static arrays*/
 	switch(iv){
-		case 0:
-			coord1=1; coord2=0; coord3=0;
+		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;
+		default: _error_("vertex index should be in [0 2]");
+	}
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussNode{{{*/
+void GaussTria::GaussNode(int numnodes,int iv){
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(numnodes){
+		case 3: //P1 Lagrange element
+			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;
+				default: _error_("node index should be in [0 2]");
+			}
 			break;
-		case 1:
-			coord1=0; coord2=1; coord3=0;
+		case 6: //P2 Lagrange element
+			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=0.; coord2=.5; coord3=.5; break;
+				case 4: coord1=.5; coord2=0.; coord3=.5; break;
+				case 5: coord1=.5; coord2=.5; coord3=0.; break;
+				default: _error_("node index should be in [0 5]");
+			}
 			break;
-		case 2:
-			coord1=0; coord2=0; coord3=1;
-			break;
-		default:
-			_error_("vertex index should be in [0 2]");
-
+		default: _error_("supported number of nodes are 3 and 6");
 	}
 
Index: /issm/trunk/src/c/classes/gauss/GaussTria.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 15395)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 15396)
@@ -7,7 +7,5 @@
 
 /*Headers:*/
-/*{{{*/
-#include "./../../shared/shared.h"
-/*}}}*/
+#include "../../shared/Numerics/types.h"
 
 class GaussTria{
@@ -15,11 +13,11 @@
 	private:
 		int numgauss;
-		IssmPDouble* weights;
-		IssmPDouble* coords1;
-		IssmPDouble* coords2;
-		IssmPDouble* coords3;
+		IssmDouble* weights;
+		IssmDouble* coords1;
+		IssmDouble* coords2;
+		IssmDouble* coords3;
 
 	public:
-		IssmPDouble weight;
+		IssmDouble weight;
 		IssmDouble coord1;
 		IssmDouble coord2;
@@ -32,4 +30,5 @@
 		GaussTria(int order);
 		GaussTria(int index1,int index2,int order);
+		GaussTria(int index,IssmDouble r1, IssmDouble r2,bool maintlyfloating,int order);
 		~GaussTria();
 
@@ -41,4 +40,5 @@
 		void GaussPoint(int ig);
 		void GaussVertex(int iv);
+		void GaussNode(int numnodes,int iv);
 		void GaussCenter(void);
 		void GaussEdgeCenter(int index1,int index2);
Index: /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 15396)
@@ -9,10 +9,6 @@
 #endif
 
-#include <stdio.h>
-#include <string.h>
-#include "../objects/objects.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../classes.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 
 /*ExponentialVariogram constructors and destructor*/
@@ -51,8 +47,8 @@
 /*FUNCTION ExponentialVariogram::Echo {{{*/
 void ExponentialVariogram::Echo(void){
-	_printLine_("ExponentialVariogram");
-	_printLine_("   nugget: " << this->nugget);
-	_printLine_("   sill  : " << this->sill);
-	_printLine_("   range : " << this->range);
+	_printf_("ExponentialVariogram\n");
+	_printf_("   nugget: " << this->nugget << "\n");
+	_printf_("   sill  : " << this->sill << "\n");
+	_printf_("   range : " << this->range << "\n");
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp	(revision 15396)
@@ -9,10 +9,6 @@
 #endif
 
-#include <stdio.h>
-#include <string.h>
-#include "../objects/objects.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../classes.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 
 /*GaussianVariogram constructors and destructor*/
@@ -51,8 +47,8 @@
 /*FUNCTION GaussianVariogram::Echo {{{*/
 void GaussianVariogram::Echo(void){
-	_printLine_("GaussianVariogram");
-	_printLine_("   nugget: " << this->nugget);
-	_printLine_("   sill  : " << this->sill);
-	_printLine_("   range : " << this->range);
+	_printf_("GaussianVariogram\n");
+	_printf_("   nugget: " << this->nugget << "\n");
+	_printf_("   sill  : " << this->sill << "\n");
+	_printf_("   range : " << this->range << "\n");
 }
 /*}}}*/
@@ -93,6 +89,6 @@
 	gamma = (sill-nugget)*(1.-exp(-h2/(a*range*range))) + nugget;
 
-	//if(h2>1000*1000) _printLine_("gamma = " << gamma << " h= " << sqrt(h2));
-	_printLine_("h = " << sqrt(h2) << " gamma = " << gamma);
+	//if(h2>1000*1000) _printf_("gamma = " << gamma << " h= " << sqrt(h2) << "\n");
+	_printf_("h = " << sqrt(h2) << " gamma = " << gamma << "\n");
 	return gamma;
 }
Index: /issm/trunk/src/c/classes/kriging/Observation.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observation.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/kriging/Observation.cpp	(revision 15396)
@@ -4,5 +4,5 @@
 
 #include <stdlib.h>
-#include "../objects/objects.h"
+#include "../classes.h"
 
 /*Observation constructors and destructor*/
@@ -35,12 +35,12 @@
 void Observation::Echo(void){
 
-	_printLine_("Observation");
-	_printLine_("   index : " << this->index);
-	_printLine_("   x     : " << this->x);
-	_printLine_("   y     : " << this->y);
-	_printLine_("   xi    : "); printbinary(this->xi); _printLine_("");
-	_printLine_("   yi    : "); printbinary(this->yi); _printLine_("");
-	_printLine_("   weight: " << this->weight);
-	_printLine_("   value : " << this->value);
+	_printf_("Observation\n");
+	_printf_("   index : " << this->index << "\n");
+	_printf_("   x     : " << this->x << "\n");
+	_printf_("   y     : " << this->y << "\n");
+	_printf_("   xi    : \n"); printbinary(this->xi); _printf_("\n");
+	_printf_("   yi    : \n"); printbinary(this->yi); _printf_("\n");
+	_printf_("   weight: " << this->weight << "\n");
+	_printf_("   value : " << this->value << "\n");
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/kriging/Observation.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observation.h	(revision 15395)
+++ /issm/trunk/src/c/classes/kriging/Observation.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _OBSERVATION_H_
 
-#include "../objects/Object.h"
+#include "../../datastructures/datastructures.h"
 
 class Observation: public Object{
Index: /issm/trunk/src/c/classes/kriging/Observations.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 15396)
+++ /issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 15396)
@@ -0,0 +1,585 @@
+/*
+ * \file Observations.cpp
+ * \brief: Implementation of Observations class, derived from DataSet class.
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <vector>
+#include <functional>
+#include <algorithm>
+#include <iostream>
+
+#include "../Options/Options.h"
+#include "./Observations.h"
+#include "./Observation.h"
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+
+#include "./Quadtree.h"
+#include "./Variogram.h"
+#include "../../toolkits/toolkits.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Observations::Observations(){{{*/
+Observations::Observations(){
+	this->quadtree = NULL;
+	return;
+}
+/*}}}*/
+/*FUNCTION Observations::Observations(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){{{*/
+Observations::Observations(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){
+
+	/*Intermediaries*/
+	int          i,maxdepth,level,counter,index;
+	int          xi,yi;
+	IssmPDouble  xmin,xmax,ymin,ymax;
+	IssmPDouble  offset,minlength,minspacing,mintrimming,maxtrimming;
+	Observation *observation = NULL;
+
+	/*Check that observations is not empty*/
+	if(n==0) _error_("No observation found");
+
+	/*Get extrema*/
+	xmin=x[0]; ymin=y[0];
+	xmax=x[0]; ymax=y[0];
+	for(i=1;i<n;i++){
+		xmin=min(xmin,x[i]); ymin=min(ymin,y[i]);
+		xmax=max(xmax,x[i]); ymax=max(ymax,y[i]);
+	}
+	offset=0.05*(xmax-xmin); xmin-=offset; xmax+=offset;
+	offset=0.05*(ymax-ymin); ymin-=offset; ymax+=offset;
+
+	/*Get trimming limits*/
+	options->Get(&mintrimming,"mintrimming",-1.e+21);
+	options->Get(&maxtrimming,"maxtrimming",+1.e+21);
+	options->Get(&minspacing,"minspacing",0.01);
+	if(minspacing<=0) _error_("minspacing must > 0");
+
+	/*Get Minimum box size*/
+	if(options->GetOption("boxlength")){
+		options->Get(&minlength,"boxlength");
+		if(minlength<=0)_error_("boxlength should be a positive number");
+		maxdepth=reCast<int,IssmPDouble>(log(max(xmax-xmin,ymax-ymin)/minlength +1)/log(2.0));
+	}
+	else{
+		maxdepth = 30;
+		minlength=max(xmax-xmin,ymax-ymin)/IssmPDouble((1L<<maxdepth)-1);
+	}
+
+	/*Initialize Quadtree*/
+	_printf0_("Generating quadtree with a maximum box size " << minlength << " (depth=" << maxdepth << ")... ");
+	this->quadtree = new Quadtree(xmin,xmax,ymin,ymax,maxdepth);
+
+	/*Add observations one by one*/
+	counter = 0;
+	for(i=0;i<n;i++){
+
+		/*First check limits*/
+		if(observations_list[i]>maxtrimming) continue;
+		if(observations_list[i]<mintrimming) continue;
+
+		/*First check that this observation is not too close from another one*/
+		this->quadtree->ClosestObs(&index,x[i],y[i]);
+		if(index>=0){
+			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
+			if(pow(observation->x-x[i],2)+pow(observation->y-y[i],2) < minspacing) continue;
+		}
+
+		this->quadtree->IntergerCoordinates(&xi,&yi,x[i],y[i]);
+		this->quadtree->QuadtreeDepth2(&level,xi,yi);
+		if((int)level <= maxdepth){
+			observation = new Observation(x[i],y[i],xi,yi,counter++,observations_list[i]);
+			this->quadtree->Add(observation);
+			this->AddObject(observation);
+		}
+		else{
+			/*We need to average with the current observations*/
+			this->quadtree->AddAndAverage(x[i],y[i],observations_list[i]);
+		}
+	}
+	_printf0_("done\n");
+	_printf0_("Initial number of observations: " << n << "\n");
+	_printf0_("  Final number of observations: " << this->quadtree->NbObs << "\n");
+}
+/*}}}*/
+/*FUNCTION Observations::~Observations(){{{*/
+Observations::~Observations(){
+	delete quadtree;
+	return;
+}
+/*}}}*/
+
+/*Methods*/
+/*FUNCTION Observations::ClosestObservation{{{*/
+void Observations::ClosestObservation(IssmPDouble *px,IssmPDouble *py,IssmPDouble *pobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius){
+
+	/*Output and Intermediaries*/
+	int          nobs,i,index;
+	IssmPDouble  hmin,h2,hmin2,radius2;
+	int         *indices      = NULL;
+	Observation *observation  = NULL;
+
+	/*If radius is not provided or is 0, return all observations*/
+	if(radius==0) radius=this->quadtree->root->length;
+
+	/*First, find closest point in Quadtree (fast but might not be the true closest obs)*/
+	this->quadtree->ClosestObs(&index,x_interp,y_interp);
+	if(index>=0){
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
+		hmin = sqrt((observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp));
+		if(hmin<radius) radius=hmin;
+	}
+
+	/*Compute radius square*/
+	radius2 = radius*radius;
+
+	/*Find all observations that are in radius*/
+	this->quadtree->RangeSearch(&indices,&nobs,x_interp,y_interp,radius);
+	for (i=0;i<nobs;i++){
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[i]));
+		h2 = (observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp);
+		if(i==0){
+			hmin2 = h2;
+			index = indices[i];
+		}
+		else{
+			if(h2<hmin2){
+				hmin2 = h2;
+				index = indices[i];
+			}
+		}
+	}  
+
+	/*Assign output pointer*/
+	if(index>=0){
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
+		*px=observation->x;
+		*py=observation->y;
+		*pobs=observation->value;
+	}
+	else{
+
+		*px=UNDEF;
+		*py=UNDEF;
+		*pobs=UNDEF;
+	}
+	xDelete<int>(indices);
+
+}/*}}}*/
+/*FUNCTION Observations::Distances{{{*/
+void Observations::Distances(IssmPDouble* distances,IssmPDouble *x,IssmPDouble *y,int n,IssmPDouble radius){
+
+	IssmPDouble xi,yi,obs;
+
+	for(int i=0;i<n;i++){
+		this->ClosestObservation(&xi,&yi,&obs,x[i],y[i],radius);
+		if(xi==UNDEF && yi==UNDEF)
+		 distances[i]=UNDEF;
+		else
+		 distances[i]=sqrt( (x[i]-xi)*(x[i]-xi) + (y[i]-yi)*(y[i]-yi) );
+	}
+}/*}}}*/
+/*FUNCTION Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int maxdata){{{*/
+void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int maxdata){
+
+	/*Output and Intermediaries*/
+	bool         stop;
+	int          nobs,tempnobs,i,j,k,n,counter;
+	IssmPDouble  h2,radius2;
+	int         *indices      = NULL;
+	int         *tempindices  = NULL;
+	IssmPDouble *dists        = NULL;
+	IssmPDouble *x            = NULL;
+	IssmPDouble *y            = NULL;
+	IssmPDouble *obs          = NULL;
+	Observation *observation  = NULL;
+
+	/*If radius is not provided or is 0, return all observations*/
+	if(radius==0) radius=this->quadtree->root->length;
+
+	/*Compute radius square*/
+	radius2 = radius*radius;
+
+	/*Find all observations that are in radius*/
+	this->quadtree->RangeSearch(&tempindices,&tempnobs,x_interp,y_interp,radius);
+	if(tempnobs){
+		indices = xNew<int>(tempnobs);
+		dists   = xNew<IssmPDouble>(tempnobs);
+	}
+	nobs = 0;
+	for (i=0;i<tempnobs;i++){
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(tempindices[i]));
+		h2 = (observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp);
+
+		if(nobs==maxdata && h2>radius2) continue;
+		if(nobs<=maxdata){
+			indices[nobs]   = tempindices[i];
+			dists[nobs]     = h2;
+			nobs++;
+		}
+		if(nobs==1) continue;
+
+		/*Sort all dists up to now*/
+		n=nobs-1;
+		stop = false;
+		for(k=0;k<n-1;k++){
+			if(h2<dists[k]){
+				counter=1;
+				for(int jj=k;jj<n;jj++){
+					j  = n-counter;
+					dists[j+1]   = dists[j];
+					indices[j+1] = indices[j];
+					counter++;
+				}
+				dists[k]   = h2;
+				indices[k] = tempindices[i];
+				stop = true;
+				break;
+			}
+			if(stop) break;
+		}
+	}  
+	xDelete<IssmPDouble>(dists);
+	xDelete<int>(tempindices);
+
+	if(nobs){
+		/*Allocate vectors*/
+		x   = xNew<IssmPDouble>(nobs);
+		y   = xNew<IssmPDouble>(nobs);
+		obs = xNew<IssmPDouble>(nobs);
+
+		/*Loop over all observations and fill in x, y and obs*/
+		for (i=0;i<nobs;i++){
+			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[i]));
+			observation->WriteXYObs(&x[i],&y[i],&obs[i]);
+		}
+	}
+
+	/*Assign output pointer*/
+	xDelete<int>(indices);
+	*px=x;
+	*py=y;
+	*pobs=obs;
+	*pnobs=nobs;
+}/*}}}*/
+/*FUNCTION Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs){{{*/
+void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs){
+
+	/*Output and Intermediaries*/
+	int          nobs;
+	IssmPDouble *x            = NULL;
+	IssmPDouble *y            = NULL;
+	IssmPDouble *obs          = NULL;
+	Observation *observation  = NULL;
+
+	nobs = this->Size();
+
+	if(nobs){
+		x   = xNew<IssmPDouble>(nobs);
+		y   = xNew<IssmPDouble>(nobs);
+		obs = xNew<IssmPDouble>(nobs);
+		for(int i=0;i<this->Size();i++){
+			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(i));
+			observation->WriteXYObs(&x[i],&y[i],&obs[i]);
+		}
+	}
+
+	/*Assign output pointer*/
+	*px=x;
+	*py=y;
+	*pobs=obs;
+	*pnobs=nobs;
+}/*}}}*/
+/*FUNCTION Observations::InterpolationIDW{{{*/
+void Observations::InterpolationIDW(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata,IssmPDouble power){
+
+	/*Intermediaries*/
+	int         i,n_obs;
+	IssmPDouble prediction;
+	IssmPDouble numerator,denominator,h,weight;
+	IssmPDouble *x   = NULL;
+	IssmPDouble *y   = NULL;
+	IssmPDouble *obs = NULL;
+
+	/*Some checks*/
+	_assert_(maxdata>0);
+	_assert_(pprediction);
+	_assert_(power>0);
+
+	/*If radius is not provided or is 0, return all observations*/
+	if(radius==0) radius=this->quadtree->root->length;
+
+	/*Get list of observations for current point*/
+	this->ObservationList(&x,&y,&obs,&n_obs,x_interp,y_interp,radius,maxdata);
+
+	/*If we have less observations than mindata, return UNDEF*/
+	if(n_obs<mindata){
+		prediction = UNDEF; 
+	}
+	else{
+		numerator   = 0.;
+		denominator = 0.;
+		for(i=0;i<n_obs;i++){
+			h = sqrt( (x[i]-x_interp)*(x[i]-x_interp) + (y[i]-y_interp)*(y[i]-y_interp));
+			if (h<0.0000001){
+				numerator   = obs[i];
+				denominator = 1.;
+				break;
+			}
+			weight = 1./pow(h,power);
+			numerator   += weight*obs[i];
+			denominator += weight;
+		}
+		prediction = numerator/denominator; 
+	}
+
+	/*clean-up*/
+	*pprediction = prediction;
+	xDelete<IssmPDouble>(x);
+	xDelete<IssmPDouble>(y);
+	xDelete<IssmPDouble>(obs);
+}/*}}}*/
+/*FUNCTION Observations::InterpolationKriging{{{*/
+void Observations::InterpolationKriging(IssmPDouble *pprediction,IssmPDouble *perror,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata,Variogram* variogram){
+
+	/*Intermediaries*/
+	int           i,j,n_obs;
+	IssmPDouble   prediction,error;
+	IssmPDouble   numerator,denominator,ratio;
+	IssmPDouble  *x            = NULL;
+	IssmPDouble  *y            = NULL;
+	IssmPDouble  *obs          = NULL;
+	IssmPDouble  *Gamma        = NULL;
+	IssmPDouble  *GinvG0       = NULL;
+	IssmPDouble  *Ginv1        = NULL;
+	IssmPDouble  *GinvZ        = NULL;
+	IssmPDouble  *gamma0       = NULL;
+	IssmPDouble  *ones         = NULL;
+
+	/*Some checks*/
+	_assert_(mindata>0 && maxdata>0);
+	_assert_(pprediction && perror);
+
+	/*If radius is not provided or is 0, return all observations*/
+	if(radius==0) radius=this->quadtree->root->length;
+
+	/*Get list of observations for current point*/
+	this->ObservationList(&x,&y,&obs,&n_obs,x_interp,y_interp,radius,maxdata);
+
+	/*If we have less observations than mindata, return UNDEF*/
+	if(n_obs<mindata){
+		*pprediction = -999.0; 
+		*perror      = -999.0; 
+		return;
+	}
+
+	/*Allocate intermediary matrix and vectors*/
+	Gamma  = xNew<IssmPDouble>(n_obs*n_obs);
+	gamma0 = xNew<IssmPDouble>(n_obs);
+	ones   = xNew<IssmPDouble>(n_obs);
+
+	/*First: Create semivariogram matrix for observations*/
+	for(i=0;i<n_obs;i++){
+		for(j=0;j<=i;j++){
+			//Gamma[i*n_obs+j] = variogram->SemiVariogram(x[i]-x[j],y[i]-y[j]);
+			Gamma[i*n_obs+j] = variogram->Covariance(x[i]-x[j],y[i]-y[j]);
+			Gamma[j*n_obs+i] = Gamma[i*n_obs+j];
+		}
+	}
+	for(i=0;i<n_obs;i++) ones[i]=1;
+
+	/*Get semivariogram vector associated to this location*/
+	//for(i=0;i<n_obs;i++) gamma0[i] = variogram->SemiVariogram(x[i]-x_interp,y[i]-y_interp);
+	for(i=0;i<n_obs;i++) gamma0[i] = variogram->Covariance(x[i]-x_interp,y[i]-y_interp);
+
+	/*Solve the three linear systems*/
+#if _HAVE_GSL_
+	DenseGslSolve(&GinvG0,Gamma,gamma0,n_obs); // Gamma^-1 gamma0
+	DenseGslSolve(&Ginv1, Gamma,ones,n_obs);   // Gamma^-1 ones
+	DenseGslSolve(&GinvZ, Gamma,obs,n_obs);    // Gamma^-1 Z
+#else
+	_error_("GSL is required");
+#endif
+
+	/*Prepare predictor*/
+	numerator=-1.; denominator=0.;
+	for(i=0;i<n_obs;i++) numerator  +=GinvG0[i];
+	for(i=0;i<n_obs;i++) denominator+=Ginv1[i];
+	ratio=numerator/denominator;
+
+	prediction = 0.;
+	error      = - numerator*numerator/denominator;
+	for(i=0;i<n_obs;i++) prediction += (gamma0[i]-ratio)*GinvZ[i];
+	for(i=0;i<n_obs;i++) error += gamma0[i]*GinvG0[i];
+
+	/*clean-up*/
+	*pprediction = prediction;
+	*perror = error;
+	xDelete<IssmPDouble>(x);
+	xDelete<IssmPDouble>(y);
+	xDelete<IssmPDouble>(obs);
+	xDelete<IssmPDouble>(Gamma);
+	xDelete<IssmPDouble>(gamma0);
+	xDelete<IssmPDouble>(ones);
+	xDelete<IssmPDouble>(GinvG0);
+	xDelete<IssmPDouble>(Ginv1);
+	xDelete<IssmPDouble>(GinvZ);
+
+}/*}}}*/
+/*FUNCTION Observations::InterpolationNearestNeighbor{{{*/
+void Observations::InterpolationNearestNeighbor(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius){
+
+	/*Intermediaries*/
+	IssmPDouble x,y,obs;
+
+	/*Get clostest observation*/
+	this->ClosestObservation(&x,&y,&obs,x_interp,y_interp,radius);
+
+	/*Assign output pointer*/
+	*pprediction = obs;
+}/*}}}*/
+/*FUNCTION Observations::InterpolationV4{{{*/
+void Observations::InterpolationV4(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata){
+	/* Reference:  David T. Sandwell, Biharmonic spline interpolation of GEOS-3
+	 * and SEASAT altimeter data, Geophysical Research Letters, 2, 139-142,
+	 * 1987.  Describes interpolation using value or gradient of value in any
+	 * dimension.*/
+
+	/*Intermediaries*/
+	int         i,j,n_obs;
+	IssmPDouble prediction,h;
+	IssmPDouble *x       = NULL;
+	IssmPDouble *y       = NULL;
+	IssmPDouble *obs     = NULL;
+	IssmPDouble *Green   = NULL;
+	IssmPDouble *weights = NULL;
+	IssmPDouble *g       = NULL;
+
+	/*Some checks*/
+	_assert_(maxdata>0);
+	_assert_(pprediction);
+
+	/*If radius is not provided or is 0, return all observations*/
+	if(radius==0) radius=this->quadtree->root->length;
+
+	/*Get list of observations for current point*/
+	this->ObservationList(&x,&y,&obs,&n_obs,x_interp,y_interp,radius,maxdata);
+
+	/*If we have less observations than mindata, return UNDEF*/
+	if(n_obs<mindata || n_obs<2){
+		prediction = UNDEF; 
+	}
+	else{
+
+		/*Allocate intermediary matrix and vectors*/
+		Green = xNew<IssmPDouble>(n_obs*n_obs);
+		g     = xNew<IssmPDouble>(n_obs);
+
+		/*First: distance vector*/
+		for(i=0;i<n_obs;i++){
+			h = sqrt( (x[i]-x_interp)*(x[i]-x_interp) + (y[i]-y_interp)*(y[i]-y_interp) );
+			if(h>0){
+				g[i] = h*h*(log(h)-1.);
+			}
+			else{
+				g[i] = 0.;
+			}
+		}
+
+		/*Build Green function matrix*/
+		for(i=0;i<n_obs;i++){
+			for(j=0;j<=i;j++){
+				h = sqrt( (x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j]) );
+				if(h>0){
+					Green[j*n_obs+i] = h*h*(log(h)-1.);
+				}
+				else{
+					Green[j*n_obs+i] = 0.;
+				}
+				Green[i*n_obs+j] = Green[j*n_obs+i];
+			}
+		}
+
+		/*Compute weights*/
+#if _HAVE_GSL_
+		DenseGslSolve(&weights,Green,obs,n_obs); // Green^-1 obs
+#else
+		_error_("GSL is required");
+#endif
+
+		/*Interpolate*/
+		prediction = 0;
+		for(i=0;i<n_obs;i++) prediction += weights[i]*g[i];
+
+	}
+
+	/*clean-up*/
+	*pprediction = prediction;
+	xDelete<IssmPDouble>(x);
+	xDelete<IssmPDouble>(y);
+	xDelete<IssmPDouble>(obs);
+	xDelete<IssmPDouble>(Green);
+	xDelete<IssmPDouble>(g);
+	xDelete<IssmPDouble>(weights);
+}/*}}}*/
+/*FUNCTION Observations::QuadtreeColoring{{{*/
+void Observations::QuadtreeColoring(IssmPDouble* A,IssmPDouble *x,IssmPDouble *y,int n){
+
+	int xi,yi,level;
+
+	for(int i=0;i<n;i++){
+		this->quadtree->IntergerCoordinates(&xi,&yi,x[i],y[i]);
+		this->quadtree->QuadtreeDepth(&level,xi,yi);
+		A[i]=(IssmPDouble)level;
+	}
+
+}/*}}}*/
+/*FUNCTION Observations::Variomap{{{*/
+void Observations::Variomap(IssmPDouble* gamma,IssmPDouble *x,int n){
+
+	/*Output and Intermediaries*/
+	int          i,j,k;
+	IssmPDouble  distance;
+	Observation *observation1 = NULL;
+	Observation *observation2 = NULL;
+
+	IssmPDouble *counter = xNew<IssmPDouble>(n);
+	for(j=0;j<n;j++) counter[j] = 0.0;
+	for(j=0;j<n;j++) gamma[j]   = 0.0;
+
+	for(i=0;i<this->Size();i++){
+		observation1=dynamic_cast<Observation*>(this->GetObjectByOffset(i));
+
+		for(j=i+1;j<this->Size();j++){
+			observation2=dynamic_cast<Observation*>(this->GetObjectByOffset(j));
+
+			distance=sqrt(pow(observation1->x - observation2->x,2.) + pow(observation1->y - observation2->y,2.));
+			if(distance>x[n-1]) continue;
+
+			int index = int(distance/(x[1]-x[0]));
+			if(index>n-1) index = n-1;
+			if(index<0)   index = 0;
+
+			gamma[index]   += 1./2.*pow(observation1->value - observation2->value,2.);
+			counter[index] += 1.;
+		}
+	}
+
+	/*Normalize semivariogram*/
+	gamma[0]=0.;
+	for(k=0;k<n;k++){
+		if(counter[k]) gamma[k] = gamma[k]/counter[k];
+	}
+
+	/*Assign output pointer*/
+	xDelete<IssmPDouble>(counter);
+}/*}}}*/
Index: /issm/trunk/src/c/classes/kriging/Observations.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observations.h	(revision 15396)
+++ /issm/trunk/src/c/classes/kriging/Observations.h	(revision 15396)
@@ -0,0 +1,40 @@
+#ifndef _CONTAINER_OBSERVATIONS_H_
+#define  _CONTAINER_OBSERVATIONS_H_
+
+class Quadtree;
+class Variogram;
+class Options;
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+
+/*!\brief Declaration of Observations class.
+ *
+ * Declaration of Observations class.  Observations are vector lists (Containers) of Observation objects.
+ */ 
+
+class Observations: public DataSet{
+
+	private:
+		Quadtree* quadtree;
+
+	public:
+
+		/*constructors, destructors*/
+		Observations();
+		Observations(IssmDouble* observations_list,IssmDouble* x,IssmDouble* y,int n,Options* options);
+		~Observations();
+
+		/*Methods*/
+		void ClosestObservation(IssmDouble *px,IssmDouble *py,IssmDouble *pobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius);
+		void Distances(IssmPDouble* distances,IssmPDouble *x,IssmPDouble *y,int n,IssmPDouble radius);
+		void InterpolationIDW(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int mindata,int maxdata,IssmDouble power);
+		void InterpolationV4(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int mindata,int maxdata);
+		void InterpolationKriging(IssmDouble *pprediction,IssmDouble *perror,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int mindata,int maxdata,Variogram* variogram);
+		void InterpolationNearestNeighbor(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius);
+		void ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs);
+		void ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int maxdata);
+		void QuadtreeColoring(IssmDouble* A,IssmDouble *x,IssmDouble *y,int n);
+		void Variomap(IssmDouble* gamma,IssmDouble *x,int n);
+
+};
+#endif //ifndef _OBSERVATIONS_H_
Index: /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp	(revision 15396)
@@ -9,10 +9,6 @@
 #endif
 
-#include <stdio.h>
-#include <string.h>
-#include "../objects/objects.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../classes.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 
 /*PowerVariogram constructors and destructor*/
@@ -52,8 +48,8 @@
 /*FUNCTION PowerVariogram::Echo {{{*/
 void PowerVariogram::Echo(void){
-	_printLine_("PowerVariogram");
-	_printLine_("   nugget: " << this->nugget);
-	_printLine_("   slope : " << this->slope);
-	_printLine_("   power : " << this->power);
+	_printf_("PowerVariogram\n");
+	_printf_("   nugget: " << this->nugget << "\n");
+	_printf_("   slope : " << this->slope << "\n");
+	_printf_("   power : " << this->power << "\n");
 }
 /*}}}*/
@@ -89,5 +85,5 @@
 	gamma = this->nugget + this->slope*pow(h,this->power);
 
-	//if(h>1000) _printLine_("gamma = " << gamma << " h=" << h);
+	//if(h>1000) _printf_("gamma = " << gamma << " h=" << h << "\n");
 	return gamma;
 }
Index: /issm/trunk/src/c/classes/kriging/Quadtree.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 15396)
@@ -1,3 +1,3 @@
-#include "../objects/objects.h"
+#include "../classes.h"
 
 /*DOCUMENTATION What is a Quadtree? {{{
@@ -297,9 +297,9 @@
 void  Quadtree::Echo(void){
 
-	_printLine_("Quadtree:");
-	_printLine_("   MaxDepth      = " << this->MaxDepth);
-	_printLine_("   NbQuadtreeBox = " << this->NbQuadtreeBox);
-	_printLine_("   NbObs         = " << this->NbObs);
-	_printLine_("   root          = " << this->root);
+	_printf_("Quadtree:\n");
+	_printf_("   MaxDepth      = " << this->MaxDepth << "\n");
+	_printf_("   NbQuadtreeBox = " << this->NbQuadtreeBox << "\n");
+	_printf_("   NbObs         = " << this->NbObs << "\n");
+	_printf_("   root          = " << this->root << "\n");
 
 }/*}}}*/
@@ -307,9 +307,9 @@
 void  Quadtree::DeepEcho(void){
 
-	_printLine_("Quadtree:");
-	_printLine_("   MaxDepth      = " << this->MaxDepth);
-	_printLine_("   NbQuadtreeBox = " << this->NbQuadtreeBox);
-	_printLine_("   NbObs         = " << this->NbObs);
-	_printLine_("   root          = " << this->root);
+	_printf_("Quadtree:\n");
+	_printf_("   MaxDepth      = " << this->MaxDepth << "\n");
+	_printf_("   NbQuadtreeBox = " << this->NbQuadtreeBox << "\n");
+	_printf_("   NbObs         = " << this->NbObs << "\n");
+	_printf_("   root          = " << this->root << "\n");
 	boxcontainer->Echo();
 
@@ -512,9 +512,9 @@
 void  Quadtree::QuadtreeBox::Echo(void){
 
-	_printLine_("QuadtreeBox:");
-	_printLine_("   nbitems = " << this->nbitems);
-	_printLine_("   xcenter = " << this->xcenter);
-	_printLine_("   ycenter = " << this->ycenter);
-	_printLine_("   length  = " << this->length);
+	_printf_("QuadtreeBox:\n");
+	_printf_("   nbitems = " << this->nbitems << "\n");
+	_printf_("   xcenter = " << this->xcenter << "\n");
+	_printf_("   ycenter = " << this->ycenter << "\n");
+	_printf_("   length  = " << this->length << "\n");
 
 }/*}}}*/
Index: /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp	(revision 15396)
@@ -9,10 +9,6 @@
 #endif
 
-#include <stdio.h>
-#include <string.h>
-#include "../objects/objects.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../classes.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 
 /*SphericalVariogram constructors and destructor*/
@@ -51,8 +47,8 @@
 /*FUNCTION SphericalVariogram::Echo {{{*/
 void SphericalVariogram::Echo(void){
-	_printLine_("SphericalVariogram");
-	_printLine_("   nugget: " << this->nugget);
-	_printLine_("   sill  : " << this->sill);
-	_printLine_("   range : " << this->range);
+	_printf_("SphericalVariogram\n");
+	_printf_("   nugget: " << this->nugget << "\n");
+	_printf_("   sill  : " << this->sill << "\n");
+	_printf_("   range : " << this->range << "\n");
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/kriging/Variogram.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Variogram.h	(revision 15395)
+++ /issm/trunk/src/c/classes/kriging/Variogram.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _VARIOGRAM_H_
 
-#include "../objects/Object.h"
+#include "../../datastructures/datastructures.h"
 
 class Variogram: public Object{
Index: /issm/trunk/src/c/classes/kriging/krigingobjects.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/krigingobjects.h	(revision 15395)
+++ /issm/trunk/src/c/classes/kriging/krigingobjects.h	(revision 15396)
@@ -14,4 +14,5 @@
 #include "./Quadtree.h"
 #include "./Observation.h"
+#include "./Observations.h"
 
 #endif
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 15396)
@@ -15,6 +15,4 @@
 #include "../classes.h"
 #include "../../shared/shared.h"
-#include "../../Container/Container.h"
-#include "../../include/include.h"
 /*}}}*/
 
@@ -251,4 +249,7 @@
 	IssmDouble* localvalues=NULL;
 
+	/*Check that Kff has been alocated in debugging mode*/
+	_assert_(Kff);
+
 	/*If Kfs is not provided, call the other function*/
 	if(!Kfs){
@@ -376,43 +377,43 @@
 
 	int i,j;
-	_printLine_("Element Matrix echo:");
-	_printLine_("   nrows: " << this->nrows);
-	_printLine_("   ncols: " << this->ncols);
-	_printLine_("   dofsymmetrical: " << (dofsymmetrical?"true":"false"));
-
-	_printLine_("   values:");
+	_printf_("Element Matrix echo:\n");
+	_printf_("   nrows: " << this->nrows << "\n");
+	_printf_("   ncols: " << this->ncols << "\n");
+	_printf_("   dofsymmetrical: " << (dofsymmetrical?"true":"false") << "\n");
+
+	_printf_("   values:\n");
 	for(i=0;i<nrows;i++){
-		_printString_(setw(4) << right << i << ": ");
-		for(j=0;j<ncols;j++) _printString_( " " << setw(11) << setprecision (5) << right << values[i*ncols+j]);
-		_printLine_("");
-	}
-
-	_printString_("   gglobaldoflist (" << gglobaldoflist << "): ");
-	if(gglobaldoflist) for(i=0;i<nrows;i++) _printString_(" " << gglobaldoflist[i]); _printLine_("");
-
-	_printLine_("   row_fsize: " << row_fsize);
-	_printString_("   row_flocaldoflist  (" << row_flocaldoflist << "): ");
-	if(row_flocaldoflist) for(i=0;i<row_fsize;i++) _printString_(" " << row_flocaldoflist[i]); _printLine_(" ");
-	_printString_("   row_fglobaldoflist  (" << row_fglobaldoflist << "): ");
-	if(row_fglobaldoflist) for(i=0;i<row_fsize;i++) _printString_(" " << row_fglobaldoflist[i]); _printLine_(" ");
-
-	_printLine_("   row_ssize: " << row_ssize);
-	_printString_("   row_slocaldoflist  (" << row_slocaldoflist << "): ");
-	if(row_slocaldoflist) for(i=0;i<row_ssize;i++) _printString_(" " << row_slocaldoflist[i]); _printLine_(" ");
-	_printString_("   row_sglobaldoflist  (" << row_sglobaldoflist << "): ");
-	if(row_sglobaldoflist) for(i=0;i<row_ssize;i++) _printString_(" " << row_sglobaldoflist[i]); _printLine_(" ");
+		_printf_(setw(4) << right << i << ": ");
+		for(j=0;j<ncols;j++) _printf_( " " << setw(11) << setprecision (5) << right << values[i*ncols+j]);
+		_printf_("\n");
+	}
+
+	_printf_("   gglobaldoflist (" << gglobaldoflist << "): ");
+	if(gglobaldoflist) for(i=0;i<nrows;i++) _printf_(" " << gglobaldoflist[i] << "\n"); _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");
+	_printf_("   row_fglobaldoflist  (" << row_fglobaldoflist << "): ");
+	if(row_fglobaldoflist) for(i=0;i<row_fsize;i++) _printf_(" " << row_fglobaldoflist[i] << "\n"); _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");
+	_printf_("   row_sglobaldoflist  (" << row_sglobaldoflist << "): ");
+	if(row_sglobaldoflist) for(i=0;i<row_ssize;i++) _printf_(" " << row_sglobaldoflist[i] << "\n"); _printf_(" \n");
 
 	if(!dofsymmetrical){
-		_printLine_("   col_fsize: " << col_fsize);
-		_printString_("   col_flocaldoflist  (" << col_flocaldoflist << "): ");
-		if(col_flocaldoflist) for(i=0;i<col_fsize;i++) _printString_(" " << col_flocaldoflist[i]); _printLine_(" ");
-		_printString_("   col_fglobaldoflist  (" << col_fglobaldoflist << "): ");
-		if(col_fglobaldoflist) for(i=0;i<col_fsize;i++) _printString_(" " << col_fglobaldoflist[i]); _printLine_(" ");
-
-		_printLine_("   col_ssize: " << col_ssize);
-		_printString_("   col_slocaldoflist  (" << col_slocaldoflist << "): ");
-		if(col_slocaldoflist) for(i=0;i<col_ssize;i++) _printString_(" " << col_slocaldoflist[i]); _printLine_(" ");
-		_printString_("   col_sglobaldoflist  (" << col_sglobaldoflist << "): ");
-		if(col_sglobaldoflist) for(i=0;i<col_ssize;i++) _printString_(" " << col_sglobaldoflist[i]); _printLine_(" ");
+		_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");
+		_printf_("   col_fglobaldoflist  (" << col_fglobaldoflist << "): ");
+		if(col_fglobaldoflist) for(i=0;i<col_fsize;i++) _printf_(" " << col_fglobaldoflist[i] << "\n"); _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");
+		_printf_("   col_sglobaldoflist  (" << col_sglobaldoflist << "): ");
+		if(col_sglobaldoflist) for(i=0;i<col_ssize;i++) _printf_(" " << col_sglobaldoflist[i] << "\n"); _printf_(" \n");
 	}
 }
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 15395)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 15396)
@@ -11,7 +11,7 @@
 /*Headers:*/
 /*{{{*/
-#include "../objects/Object.h"
+#include "../../datastructures/datastructures.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
 class Node;
 template <class doublematrix> class Matrix;
Index: /issm/trunk/src/c/classes/matrix/ElementVector.cpp
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementVector.cpp	(revision 15395)
+++ /issm/trunk/src/c/classes/matrix/ElementVector.cpp	(revision 15396)
@@ -15,6 +15,4 @@
 #include "../classes.h"
 #include "../../shared/shared.h"
-#include "../../Container/Container.h"
-#include "../../include/include.h"
 /*}}}*/
 
@@ -221,22 +219,22 @@
 	int i;
 
-	_printLine_("Element Vector echo:");
-	_printLine_("   nrows: " << nrows);
-	_printLine_("   values:");
+	_printf_("Element Vector echo:\n");
+	_printf_("   nrows: " << nrows << "\n");
+	_printf_("   values:\n");
 	for(i=0;i<nrows;i++){
-		_printLine_(setw(4) << right << i << ": " << setw(10) << values[i]);
-	}
-
-	_printString_("   gglobaldoflist (" << gglobaldoflist << "): ");
-	if(gglobaldoflist) for(i=0;i<nrows;i++) _printString_(" " << gglobaldoflist[i] );
-	_printLine_(" ");
-
-	_printLine_("   fsize: " << fsize);
-	_printString_("   flocaldoflist  (" << flocaldoflist << "): ");
-	if(flocaldoflist) for(i=0;i<fsize;i++) _printString_(" " << flocaldoflist[i] );
-	_printLine_(" ");
-	_printString_("   fglobaldoflist (" << fglobaldoflist << "): ");
-	if(fglobaldoflist) for(i=0;i<fsize;i++) _printString_(" " << fglobaldoflist[i] );
-	_printLine_(" ");
+		_printf_(setw(4) << right << i << ": " << setw(10) << values[i] << "\n");
+	}
+
+	_printf_("   gglobaldoflist (" << gglobaldoflist << "): ");
+	if(gglobaldoflist) for(i=0;i<nrows;i++) _printf_(" " << gglobaldoflist[i] );
+	_printf_(" \n");
+
+	_printf_("   fsize: " << fsize << "\n");
+	_printf_("   flocaldoflist  (" << flocaldoflist << "): ");
+	if(flocaldoflist) for(i=0;i<fsize;i++) _printf_(" " << flocaldoflist[i] );
+	_printf_(" \n");
+	_printf_("   fglobaldoflist (" << fglobaldoflist << "): ");
+	if(fglobaldoflist) for(i=0;i<fsize;i++) _printf_(" " << fglobaldoflist[i] );
+	_printf_(" \n");
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/matrix/ElementVector.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementVector.h	(revision 15395)
+++ /issm/trunk/src/c/classes/matrix/ElementVector.h	(revision 15396)
@@ -11,7 +11,7 @@
 /*Headers:*/
 /*{{{*/
-#include "../objects/Object.h"
+#include "../../datastructures/datastructures.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
 class Node;
 template <class doubletype> class Vector;
Index: sm/trunk/src/c/classes/matrix/Matrix.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/Matrix.h	(revision 15395)
+++ 	(revision )
@@ -1,379 +1,0 @@
-/*!\file:  Matrix.h
- * \brief wrapper to matrix objects. The goal is to control which API (PETSc,Scalpack, Plapack?) 
- * implements our underlying matrix format.
- */ 
-
-#ifndef _MATRIX_H_
-#define _MATRIX_H_
-
-/*Headers:*/
-/*{{{*/
-#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 "../../EnumDefinitions/EnumDefinitions.h"
-/*}}}*/
-
-enum matrixtype { PetscMatType, SeqMatType };
-
-template <class doubletype> class Vector;
-
-template <class doubletype> 
-class Matrix{
-
-	public:
-
-		#ifdef _HAVE_PETSC_
-		PetscMat *pmatrix;
-		#endif
-		SeqMat<doubletype>   *smatrix;
-		int       type;
-
-		/*Matrix constructors, destructors*/
-		/*FUNCTION Matrix(){{{*/
-		Matrix(){
-
-			#ifdef _HAVE_PETSC_
-			pmatrix=NULL;
-			#endif
-			smatrix=NULL;
-
-			type=PetscMatType; //default
-			#ifndef _HAVE_PETSC_
-			type=SeqMatType;
-			#endif
-
-		}
-		/*}}}*/
-		/*FUNCTION Matrix(int M,int N,int in_type){{{*/
-		#ifdef _HAVE_PETSC_
-		Matrix(int M,int N,int in_type=PetscMatType){
-		#else
-		Matrix(int M,int N,int in_type=SeqMatType){
-		#endif
-
-			#ifdef _HAVE_PETSC_
-			pmatrix=NULL;
-			#endif
-			smatrix=NULL;
-			type=in_type;
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix=new PetscMat(M,N);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix=new SeqMat<doubletype>(M,N);
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz,int type){{{*/
-		#ifdef _HAVE_PETSC_
-		Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz,int in_type=PetscMatType){
-		#else
-		Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz,int in_type=SeqMatType){
-		#endif
-
-			#ifdef _HAVE_PETSC_
-			pmatrix=NULL;
-			#endif
-			smatrix=NULL;
-			type=in_type;
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix=new PetscMat(m,n,M,N,d_nnz,o_nnz);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix=new SeqMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION Matrix(int M,int N,IssmDouble sparsity,int in_type){{{*/
-		#ifdef _HAVE_PETSC_
-		Matrix(int M,int N,double sparsity,int in_type=PetscMatType){
-		#else
-		Matrix(int M,int N,double sparsity,int in_type=SeqMatType){
-		#endif
-
-			#ifdef _HAVE_PETSC_
-			pmatrix=NULL;
-			#endif
-
-			smatrix=NULL;
-			type=in_type;
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix=new PetscMat(M,N,sparsity);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix=new SeqMat<doubletype>(M,N,sparsity);
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-		}
-		/*}}}*/
-		/*FUNCTION Matrix(IssmDouble* serial_mat, int M,int N,IssmDouble sparsity,int in_type){{{*/
-		#ifdef _HAVE_PETSC_
-		Matrix(IssmPDouble* serial_mat,int M,int N,IssmPDouble sparsity,int in_type=PetscMatType){
-		#else
-		Matrix(IssmPDouble* serial_mat,int M,int N,IssmPDouble sparsity,int in_type=SeqMatType){
-		#endif
-
-			#ifdef _HAVE_PETSC_
-			pmatrix=NULL;
-			#endif
-			smatrix=NULL;
-			type=in_type;
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix=new PetscMat(serial_mat,M,N,sparsity);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix=new SeqMat<doubletype>(serial_mat,M,N,sparsity);
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION Matrix(int M,int N,int connectivity,int numberofdofspernode,int in_type){{{*/
-		#ifdef _HAVE_PETSC_
-		Matrix(int M,int N,int connectivity,int numberofdofspernode,int in_type=PetscMatType){
-		#else
-		Matrix(int M,int N,int connectivity,int numberofdofspernode,int in_type=SeqMatType){
-		#endif
-
-			#ifdef _HAVE_PETSC_
-			pmatrix=NULL;
-			#endif
-			smatrix=NULL;
-			type=in_type;
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix=new PetscMat(M,N,connectivity,numberofdofspernode);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix=new SeqMat<doubletype>(M,N,connectivity,numberofdofspernode);
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION ~Matrix(){{{*/
-		~Matrix(){
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				delete this->pmatrix;
-				#endif
-			}
-			else if(type==SeqMatType){
-				delete this->smatrix;
-			}
-
-		}
-		/*}}}*/
-
-		/*Matrix specific routines:*/
-		/*FUNCTION Echo{{{*/
-		void Echo(void){
-			_assert_(this);
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix->Echo();
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix->Echo();
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION AllocationInfo{{{*/
-		void AllocationInfo(void){
-			_assert_(this);
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix->AllocationInfo();
-				#endif
-			}
-			else if(type==SeqMatType){
-				//this->smatrix->AllocationInfo();
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-		}/*}}}*/
-		/*FUNCTION Assemble{{{*/
-		void Assemble(void){
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix->Assemble();
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix->Assemble();
-			}
-			else{
-				_error_("Matrix type: " << type << " not supported yet!");
-			}
-		}
-		/*}}}*/
-		/*FUNCTION Norm{{{*/
-		IssmDouble Norm(NormMode norm_type){
-
-			IssmDouble norm=0;
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				norm=this->pmatrix->Norm(norm_type);
-				#endif
-			}
-			else if(type==SeqMatType){
-				norm=this->smatrix->Norm(norm_type);
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-			return norm;
-		}
-		/*}}}*/
-		/*FUNCTION GetSize{{{*/
-		void GetSize(int* pM,int* pN){
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix->GetSize(pM,pN);
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix->GetSize(pM,pN);
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION GetLocalSize{{{*/
-		void GetLocalSize(int* pM,int* pN){
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix->GetLocalSize(pM,pN);
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix->GetLocalSize(pM,pN);
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION MatMult{{{*/
-		void MatMult(Vector<doubletype>* X,Vector<doubletype>* AX){
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix->MatMult(X->pvector,AX->pvector);
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix->MatMult(X->svector,AX->svector);
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION Duplicate{{{*/
-		Matrix* Duplicate(void){
-
-			Matrix* output=new Matrix();
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				output->pmatrix=this->pmatrix->Duplicate();
-				#endif
-			}
-			else if(type==SeqMatType){
-				output->smatrix=this->smatrix->Duplicate();
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-			return output;
-		}
-		/*}}}*/
-		/*FUNCTION ToSerial{{{*/
-		doubletype* ToSerial(void){
-
-			doubletype* output=NULL;
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				output=this->pmatrix->ToSerial();
-				#endif
-			}
-			else if(type==SeqMatType){
-				output=this->smatrix->ToSerial();
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-
-			return output;
-		}
-		/*}}}*/
-		/*FUNCTION SetValues{{{*/
-		void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix->SetValues(m,idxm,n,idxn,values,mode);
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix->SetValues(m,idxm,n,idxn,values,mode);
-			}
-			else _error_("Matrix type: " << type << " not supported yet!");
-		}
-		/*}}}*/
-		/*FUNCTION Convert{{{*/
-		void Convert(MatrixType newtype){
-
-			if(type==PetscMatType){
-				#ifdef _HAVE_PETSC_
-				this->pmatrix->Convert(newtype);
-				#endif
-			}
-			else if(type==SeqMatType){
-				this->smatrix->Convert(newtype);
-			}
-			else{
-				_error_("Matrix type: " << type << " not supported yet!");
-			}
-
-		}
-		/*}}}*/
-};
-
-#endif //#ifndef _MATRIX_H_
Index: sm/trunk/src/c/classes/matrix/Vector.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/Vector.h	(revision 15395)
+++ 	(revision )
@@ -1,478 +1,0 @@
-/*!\file:  Vector.h
- * \brief wrapper to vector objects. The goal is to control which API (PETSc,Scalpack, Plapack?) 
- * implements our underlying vector format.
- */ 
-
-#ifndef _VECTOR_H_
-#define _VECTOR_H_
-
-/*Headers:*/
-/*{{{*/
-#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 "../../EnumDefinitions/EnumDefinitions.h"
-
-/*}}}*/
-
-enum vectortype { PetscVecType, SeqVecType };
-
-template <class doubletype> 
-class Vector{
-
-	public:
-
-		int  type;
-		#ifdef _HAVE_PETSC_
-		PetscVec* pvector;
-		#endif
-		SeqVec<doubletype>* svector; 
-
-		/*Vector constructors, destructors */
-		/*FUNCTION Vector(){{{*/
-		Vector(){
-
-			#ifdef _HAVE_PETSC_
-			this->pvector=NULL;
-			#endif
-			this->svector=NULL;
-
-			type=PetscVecType; //default
-			#ifndef _HAVE_PETSC_
-			type=SeqVecType;
-			#endif
-
-		}
-		/*}}}*/
-		/*FUNCTION Vector(int M,bool fromlocalsize,int in_type){{{*/
-		#ifdef _HAVE_PETSC_
-		Vector(int M,bool fromlocalsize=false,int in_type=PetscVecType){
-		#else
-		Vector(int M,bool fromlocalsize=false,int in_type=SeqVecType){
-		#endif
-
-			#ifdef _HAVE_PETSC_
-			pvector=NULL;
-			#endif
-			svector=NULL;
-			type=in_type;
-
-			if(type==PetscVecType){
-			#ifdef _HAVE_PETSC_
-				this->pvector=new PetscVec(M,fromlocalsize);
-			 #else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-			 #endif
-			}
-			else if(type==SeqVecType){
-				this->svector=new SeqVec<doubletype>(M,fromlocalsize);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION Vector(int m,int M,int in_type){{{*/
-		#ifdef _HAVE_PETSC_
-		Vector(int m,int M,int in_type=PetscVecType){
-		#else
-		Vector(int m,int M,int in_type=SeqVecType){
-		#endif
-
-			#ifdef _HAVE_PETSC_
-			pvector=NULL;
-			#endif
-			svector=NULL;
-			type=in_type;
-
-			if(type==PetscVecType){
-			#ifdef _HAVE_PETSC_
-				this->pvector=new PetscVec(m,M);
-			 #else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-			 #endif
-			}
-			else if(type==SeqVecType){
-				this->svector=new SeqVec<doubletype>(m,M);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION Vector(doubletype* serial_vec,int M,int in_type){{{*/
-		#ifdef _HAVE_PETSC_
-		Vector(doubletype* serial_vec,int M,int in_type=PetscVecType){
-		#else
-		Vector(doubletype* serial_vec,int M,int in_type=SeqVecType){
-			//} for vim
-		#endif
-
-			#ifdef _HAVE_PETSC_
-			pvector=NULL;
-			#endif
-
-			svector=NULL;
-			type=in_type;
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector=new PetscVec(serial_vec,M);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector=new SeqVec<doubletype>(serial_vec,M);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION ~Vector(){{{*/
-		~Vector(){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				delete this->pvector;
-				#endif
-			}
-			else if(type==SeqVecType){
-				delete this->svector;
-			}
-		}
-		/*}}}*/
-		#ifdef _HAVE_PETSC_
-		/*FUNCTION Vector(Vec petsc_vector){{{*/
-		Vector(Vec petsc_vector){
-
-			this->type=PetscVecType;
-			this->svector=NULL;
-			this->pvector=new PetscVec(petsc_vector);
-
-		}
-		/*}}}*/
-		#endif
-
-		/*Vector specific routines*/
-		/*FUNCTION Echo{{{*/
-		void Echo(void){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->Echo();
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->Echo();
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION Assemble{{{*/
-		void Assemble(void){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->Assemble();
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->Assemble();
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION SetValues{{{*/
-		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->SetValues(ssize,list,values,mode);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->SetValues(ssize,list,values,mode);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION SetValue{{{*/
-		void SetValue(int dof, doubletype value, InsMode mode){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->SetValue(dof,value,mode);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->SetValue(dof,value,mode);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION GetValue{{{*/
-		void GetValue(doubletype* pvalue,int dof){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->GetValue(pvalue,dof);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->GetValue(pvalue,dof);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION GetSize{{{*/
-		void GetSize(int* pM){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->GetSize(pM);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->GetSize(pM);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION IsEmpty{{{*/
-		bool IsEmpty(void){
-
-			int M;
-
-			this->GetSize(&M);
-
-			if(M==0) 
-				return true;
-			else
-				return false;
-		}
-		/*}}}*/
-		/*FUNCTION GetLocalSize{{{*/
-		void GetLocalSize(int* pM){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->GetLocalSize(pM);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->GetLocalSize(pM);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION Duplicate{{{*/
-		Vector* Duplicate(void){
-
-			Vector* output=NULL;
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				output=new Vector();
-				output->pvector=this->pvector->Duplicate();
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				output=new Vector();
-				output->svector=this->svector->Duplicate();
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-			return output;
-
-		}
-		/*}}}*/
-		/*FUNCTION Set{{{*/
-		void Set(doubletype value){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->Set(value);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->Set(value);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION AXPY{{{*/
-		void AXPY(Vector* X, doubletype a){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->AXPY(X->pvector,a);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->AXPY(X->svector,a);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION AYPX{{{*/
-		void AYPX(Vector* X, doubletype a){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->AYPX(X->pvector,a);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->AYPX(X->svector,a);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION ToMPISerial{{{*/
-		doubletype* ToMPISerial(void){
-
-			doubletype* vec_serial=NULL;
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				vec_serial=this->pvector->ToMPISerial();
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				vec_serial=this->svector->ToMPISerial();
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-			return vec_serial;
-
-		}
-		/*}}}*/
-		/*FUNCTION Copy{{{*/
-		void Copy(Vector* to){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->Copy(to->pvector);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->Copy(to->svector);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION Norm{{{*/
-		doubletype Norm(NormMode norm_type){
-
-			doubletype norm=0;
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				norm=this->pvector->Norm(norm_type);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				norm=this->svector->Norm(norm_type);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-			return norm;
-		}
-		/*}}}*/
-		/*FUNCTION Scale{{{*/
-		void Scale(doubletype scale_factor){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->Scale(scale_factor);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->Scale(scale_factor);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-		/*FUNCTION Dot{{{*/
-		doubletype Dot(Vector* vector){
-
-			doubletype dot;
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				dot=this->pvector->Dot(vector->pvector);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				dot=this->svector->Dot(vector->svector);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-			return dot;
-		}
-		/*}}}*/
-		/*FUNCTION PointwiseDivide{{{*/
-		void PointwiseDivide(Vector* x,Vector* y){
-
-			if(type==PetscVecType){
-				#ifdef _HAVE_PETSC_
-				this->pvector->PointwiseDivide(x->pvector,y->pvector);
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
-				#endif
-			}
-			else if(type==SeqVecType){
-				this->svector->PointwiseDivide(x->svector,y->svector);
-			}
-			else _error_("Vector type: " << type << " not supported yet!");
-
-		}
-		/*}}}*/
-};
-#endif //#ifndef _VECTOR_H_
Index: /issm/trunk/src/c/classes/matrix/matrixobjects.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/matrixobjects.h	(revision 15395)
+++ /issm/trunk/src/c/classes/matrix/matrixobjects.h	(revision 15396)
@@ -9,6 +9,4 @@
 #include "./ElementMatrix.h"
 #include "./ElementVector.h"
-#include "./Vector.h"
-#include "./Matrix.h"
 
 #endif
Index: /issm/trunk/src/c/datastructures/DataSet.cpp
===================================================================
--- /issm/trunk/src/c/datastructures/DataSet.cpp	(revision 15396)
+++ /issm/trunk/src/c/datastructures/DataSet.cpp	(revision 15396)
@@ -0,0 +1,249 @@
+/*
+ * \file DataSet.cpp
+ * \brief: Implementation of DataSet class
+ */
+
+/*Headers: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+#include <vector>
+#include <functional>
+#include <algorithm>
+#include <iostream>
+
+#include "../datastructures/datastructures.h"
+#include "../shared/shared.h"
+
+using namespace std;
+/*}}}*/
+
+/*Constructors/Destructors*/
+/*FUNCTION DataSet::DataSet(){{{*/
+DataSet::DataSet(){
+
+	sorted=0;
+	sorted_ids=NULL;
+	id_offsets=NULL;
+
+}
+/*}}}*/
+/*FUNCTION DataSet::DataSet(int dataset_enum){{{*/
+DataSet::DataSet(int dataset_enum){
+	enum_type=dataset_enum;
+
+	sorted=0;
+	sorted_ids=NULL;
+	id_offsets=NULL;
+
+}
+/*}}}*/
+/*FUNCTION DataSet::Copy{{{*/
+DataSet*   DataSet::Copy(void){
+
+	vector<Object*>::iterator object;
+	Object* object_copy=NULL;
+
+	DataSet* copy=new DataSet(enum_type);
+
+	copy->sorted=sorted;
+	copy->presorted=presorted;
+	if(sorted_ids){
+		copy->sorted_ids=xNew<int>(objects.size());
+		xMemCpy<int>(copy->sorted_ids,sorted_ids,objects.size());
+	}
+	if(id_offsets){
+		copy->id_offsets=xNew<int>(objects.size());
+		xMemCpy<int>(copy->id_offsets,id_offsets,objects.size());
+	}
+
+	/*Now we need to deep copy the objects: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Call echo on object: */
+		object_copy = (*object)->copy();
+		copy->AddObject(object_copy);
+	}
+	return copy;
+}
+/*}}}*/
+/*FUNCTION DataSet::~DataSet{{{*/
+DataSet::~DataSet(){
+	clear();
+	xDelete<int>(sorted_ids);
+	xDelete<int>(id_offsets);
+}
+/*}}}*/
+
+/*Specific methods*/
+/*FUNCTION DataSet::AddObject{{{*/
+int  DataSet::AddObject(Object* object){
+
+	_assert_(this);
+	objects.push_back(object);
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION DataSet::clear{{{*/
+void  DataSet::clear(){
+
+/*  use reverse_iterator for efficiency in matlab memory manager
+	(keeping old code in case it needs to revert back)  */
+
+//	vector<Object*>::iterator object;
+	vector<Object*>::reverse_iterator object;
+
+//	for ( object=objects.begin() ; object < objects.end(); object++ ){
+//		delete (*object);
+//	}
+	for ( object=objects.rbegin() ; object < objects.rend(); object++ ){
+		delete (*object);
+	}
+	objects.clear();
+}
+/*}}}*/
+/*FUNCTION DataSet::DeleteObject{{{*/
+int  DataSet::DeleteObject(Object* object){
+
+	vector<Object*>::iterator iterator;
+
+	if(object){
+		iterator = find(objects.begin(), objects.end(),object);
+		delete *iterator;
+		objects.erase(iterator);
+	}
+
+	return 1;
+
+}
+/*}}}*/
+/*FUNCTION DataSet::DeepEcho{{{*/
+void DataSet::DeepEcho(){
+
+	vector<Object*>::iterator object;
+
+	if(this==NULL)_error_("trying to echo a NULL dataset");
+
+	_printf0_("DataSet echo: " << objects.size() << " objects\n");
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Call deep echo on object: */
+		(*object)->DeepEcho();
+
+	}
+}
+/*}}}*/
+/*FUNCTION DataSet::Echo{{{*/
+void DataSet::Echo(){
+
+	vector<Object*>::iterator object;
+
+	if(this==NULL)_error_("trying to echo a NULL dataset");
+
+	_printf0_("DataSet echo: " << objects.size() << " objects\n");
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Call echo on object: */
+		(*object)->Echo();
+
+	}
+	return;
+}
+/*}}}*/
+/*FUNCTION DataSet::GetEnum(){{{*/
+int  DataSet::GetEnum(){
+	return enum_type;
+}
+/*}}}*/
+/*FUNCTION DataSet::GetEnum(int offset){{{*/
+int   DataSet::GetEnum(int offset){
+
+	return objects[offset]->ObjectEnum();
+
+}
+/*}}}*/
+/*FUNCTION DataSet::GetObjectByOffset{{{*/
+Object* DataSet::GetObjectByOffset(int offset){
+
+	/*Check index in debugging mode*/
+	_assert_(this!=NULL);
+	_assert_(offset>=0);
+	_assert_(offset<this->Size());
+
+	return objects[offset];
+
+}
+/*}}}*/
+/*FUNCTION DataSet::GetObjectById{{{*/
+Object* DataSet::GetObjectById(int* poffset,int eid){
+
+	int id_offset;
+	int offset;
+
+	_assert_(this);
+	if(!sorted)_error_("trying to binary search on a non-sorted dataset!");
+
+	/*Carry out a binary search on the sorted_ids: */
+	if(!binary_search(&id_offset,eid,sorted_ids,objects.size())){
+		_error_("could not find object with id " << eid << " in DataSet " << EnumToStringx(enum_type));
+	}
+
+	/*Convert  the id offset into sorted offset: */
+	offset=id_offsets[id_offset];
+
+	/*Assign output pointers if requested:*/
+	if(poffset)*poffset=offset;
+
+	/*Return object at offset position in objects :*/
+	return objects[offset];
+}
+/*}}}*/
+/*FUNCTION DataSet::Presort{{{*/
+void DataSet::Presort(){
+
+	/*vector of objects is already sorted, just allocate the sorted ids and their
+	 * offsets:*/
+	if(objects.size()){
+
+		/*Delete existing ids*/
+		xDelete<int>(sorted_ids);
+		xDelete<int>(id_offsets);
+
+		/*Allocate new ids*/
+		sorted_ids=xNew<int>(objects.size());
+		id_offsets=xNew<int>(objects.size());
+
+		/*Build id_offsets and sorted_ids*/
+		for(int i=0;i<objects.size();i++){
+			id_offsets[i]=i;
+			sorted_ids[i]=objects[i]->Id();
+		}
+	}
+
+	/*set sorted flag: */
+	sorted=1;
+}
+/*}}}*/
+/*FUNCTION DataSet::Size{{{*/
+int  DataSet::Size(void){
+	_assert_(this!=NULL);
+
+	return objects.size();
+}
+/*}}}*/
+/*FUNCTION DataSet::Sort{{{*/
+void DataSet::Sort(){
+
+	/*Only sort if we are not already sorted: */
+	if(!sorted){
+		_error_("not implemented yet!");
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/datastructures/DataSet.h
===================================================================
--- /issm/trunk/src/c/datastructures/DataSet.h	(revision 15396)
+++ /issm/trunk/src/c/datastructures/DataSet.h	(revision 15396)
@@ -0,0 +1,53 @@
+#ifndef _CONTAINER_DATASET_H_
+#define _CONTAINER_DATASET_H_
+
+#include <vector>
+#include <cstring>
+
+/*forward declarations */
+class Object;
+
+/*! \brief Declaration of DataSet class
+ *
+ * Declaration of DataSet class.  A DataSet is a Container of Objects.
+ */
+class DataSet{
+
+	public: 
+
+		/*internals: */
+		std::vector<Object*> objects;
+
+		/*type of dataset: */
+		int             enum_type;
+
+		/*sorting: */
+		int             sorted;
+		int             presorted;
+		int*            sorted_ids;
+		int*            id_offsets;
+
+		/*constructors, destructors*/
+		DataSet();
+		DataSet(int enum_type);
+		~DataSet();
+
+		/*management*/
+		int      GetEnum();
+		int      GetEnum(int offset);
+		void     Echo();
+		void     DeepEcho();
+		int      AddObject(Object *object);
+		int      DeleteObject(int id);
+		int      Size();
+		void     clear();
+		Object  *GetObjectByOffset(int  offset);
+		Object  *GetObjectById(int *poffset,int eid);
+		void     Presort();
+		void     Sort();
+		DataSet *Copy(void);
+		int      DeleteObject(Object *object);
+
+};
+
+#endif
Index: /issm/trunk/src/c/datastructures/Object.h
===================================================================
--- /issm/trunk/src/c/datastructures/Object.h	(revision 15396)
+++ /issm/trunk/src/c/datastructures/Object.h	(revision 15396)
@@ -0,0 +1,25 @@
+/*
+ * Object.h:
+ * \brief prototype for abstract Object class
+ * \file Object.h
+ * This prototype describes the Object class. This is an abstract class, parent 
+ * to any other objects (Quad, Tria, Node , etc ...), that can be included in a 
+ * DataSet.
+ */
+
+#ifndef _OBJECT_H_
+#define _OBJECT_H_
+
+class Object {
+
+	public: 
+
+		virtual       ~Object(){};
+		virtual void  Echo()=0;
+		virtual void  DeepEcho()=0;
+		virtual int   Id()=0;
+		virtual int   ObjectEnum()=0;
+		virtual Object* copy()=0;
+
+};
+#endif
Index: /issm/trunk/src/c/datastructures/datastructures.h
===================================================================
--- /issm/trunk/src/c/datastructures/datastructures.h	(revision 15396)
+++ /issm/trunk/src/c/datastructures/datastructures.h	(revision 15396)
@@ -0,0 +1,11 @@
+/* \file datastructures.h
+ * \brief: header file for all datastructures  routines.
+ */
+
+#ifndef _DATA_STRUCTURES_H_
+#define _DATA_STRUCTURES_H_
+
+#include "./DataSet.h"
+#include "./Object.h"
+
+#endif
Index: sm/trunk/src/c/issm.h
===================================================================
--- /issm/trunk/src/c/issm.h	(revision 15395)
+++ 	(revision )
@@ -1,25 +1,0 @@
-/*!\file: issm.h
- * \brief prototype wrapper for issm.h
- */ 
-
-#ifndef _ISSM_H_
-#define _ISSM_H_
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "./include/globals.h" //only include this header file once!
-#include "./include/include.h"
-#include "./shared/shared.h"
-#include "./classes/classes.h"
-#include "./Container/Container.h"
-#include "./EnumDefinitions/EnumDefinitions.h"
-#include "./toolkits/toolkits.h"
-#include "./solutions/solutions.h"
-#include "./solvers/solvers.h"
-#include "./modules/modules.h"
-
-#endif //ifndef _ISSM_H_
Index: /issm/trunk/src/c/kml/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/kml/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/kml/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,34 @@
+# 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 15396)
+++ /issm/trunk/src/c/kml/KMLFileReadUtils.cpp	(revision 15396)
@@ -0,0 +1,720 @@
+/*!\file KMLFileUtils.cpp
+ * \brief: utilities for kml file reading.
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KMLFileReadUtils.h"
+#include "./KML_Object.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*FUNCTION  KMLFileToken(FILE* fid,int* pncom=NULL,char*** ppcom=NULL) {{{*/
+char* KMLFileToken(FILE* fid,
+				   int* pncom=NULL,char*** ppcom=NULL){
+
+/*  get the next token (tag or field) in the file  */
+
+	bool    inew=1,itag=0,ifield=0;
+	int     c;
+	int     ibuf=0,buflen=1024,bufblk=1024;
+	char    *buffer=NULL,*bufferc=NULL,**pcom2=NULL;
+
+	buffer=xNew<char>(buflen);
+	buffer[0]='\0';
+
+/*  read kml file character-by-character  */
+
+//  note that fgets includes newline
+//	fgets(buffer,buflen,fid);
+
+	while ((c=getc(fid)) != EOF) {
+		/*  ignore leading blanks  */
+		if (inew && isspace(c))
+			continue;
+
+		/*  distinguish between tag or field  */
+		if (!itag && !ifield) {
+
+			/*  distinguish between tag or comment  */
+			if (c == '<') {
+				ungetc(c,fid);
+				if (!(bufferc=KMLFileTokenComment(fid))) {
+					c=getc(fid);
+					itag=1;
+				}
+				else {
+					if (pncom && ppcom) {
+						(*pncom)++;
+						pcom2=xNew<char*>(*pncom);
+						memcpy(pcom2,*ppcom,(*pncom-1)*sizeof(char*));
+						xDelete<char*>(*ppcom);
+						*ppcom=pcom2;
+						pcom2=NULL;
+//						*ppcom=(char **) xrealloc(*ppcom,*pncom*sizeof(char*));
+						(*ppcom)[*pncom-1]=bufferc;
+					}
+					else
+						xDelete<char>(bufferc);
+					inew=1;
+					continue;
+				}
+			}
+			else
+				ifield=1;
+			inew=0;
+			KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+							   c,
+							   bufblk);
+		}
+
+		/*  accumulate tag, not including newlines  */
+		else if (itag) {
+			if (c != '\n') {
+				inew=0;
+				KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+								   c,
+								   bufblk);
+				if (c == '>')
+					break;
+			}
+			else
+				inew=1;
+		}
+
+		/*  accumulate field, including newlines  */
+		else if (ifield) {
+			/*  distinguish between another tag or comment  */
+			if (c == '<') {
+				ungetc(c,fid);
+				if (!(bufferc=KMLFileTokenComment(fid)))
+					break;
+				else
+					if (pncom && ppcom) {
+						(*pncom)++;
+						pcom2=xNew<char*>(*pncom);
+						memcpy(pcom2,*ppcom,(*pncom-1)*sizeof(char*));
+						xDelete<char*>(*ppcom);
+						*ppcom=pcom2;
+						pcom2=NULL;
+//						*ppcom=(char **) xrealloc(*ppcom,*pncom*sizeof(char*));
+						(*ppcom)[*pncom-1]=bufferc;
+					}
+					else
+						xDelete<char>(bufferc);
+			}
+			else {
+				inew=0;
+				KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+								   c,
+								   bufblk);
+				if (c == '\n')
+					inew=1;
+			}
+		}
+
+	}
+
+/*  remove trailing blanks or newline  */
+
+	while (ibuf > 0)
+		if (isspace(buffer[ibuf-1]))
+			ibuf--;
+		else {
+			buffer[ibuf]='\0';
+			break;
+		}
+
+//	if      (itag)
+//		_printf0_("tag buffer (length=" << ibuf << "):\n");
+//	else if (ifield)
+//		_printf0_("field buffer (length=" << ibuf << "):\n");
+//	_printf0_(buffer << "\n");
+
+	if (!ibuf)
+		xDelete<char>(buffer);
+
+	return(buffer);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenComment(FILE* fid) {{{*/
+char* KMLFileTokenComment(FILE* fid){
+
+/*  check for comment in the file and read it  */
+
+	bool    inew=1;
+	int     i;
+	int     c;
+	int     ibuf=0,buflen=1024,bufblk=1024;
+	char*   buffer=NULL;
+
+	buffer=xNew<char>(buflen);
+	buffer[0]='\0';
+
+/*  read kml file character-by-character  */
+
+	while ((c=getc(fid)) != EOF) {
+		/*  ignore leading blanks  */
+		if (inew && isspace(c))
+			continue;
+
+		inew=0;
+		KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+						   c,
+						   bufblk);
+
+		/*  check for comment  */
+		if (ibuf <= 4) {
+			if ((ibuf == 1 && buffer[0] != '<') ||
+				(ibuf == 2 && buffer[1] != '!') ||
+				(ibuf == 3 && buffer[2] != '-') ||
+				(ibuf == 4 && buffer[3] != '-')) {
+				for (i=ibuf-1; i>=0; i--)
+					ungetc(buffer[i],fid);
+				xDelete<char>(buffer);
+				return(buffer);
+			}
+		}
+
+		/*  accumulate comment, including newlines  */
+		else
+			if (buffer[ibuf-3]=='-' && buffer[ibuf-2]=='-' && buffer[ibuf-1]=='>')
+				break;
+	}
+
+/*  remove trailing blanks or newline  */
+
+	while (ibuf > 0)
+		if (isspace(buffer[ibuf-1]))
+			ibuf--;
+		else {
+			buffer[ibuf]='\0';
+			break;
+		}
+
+//	_printf0_("comment buffer (length=" << ibuf << "):\n");
+//	_printf0_(buffer << "\n");
+
+	if (!ibuf)
+		xDelete<char>(buffer);
+
+	return(buffer);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenBuffer {{{*/
+void KMLFileTokenBuffer(char** pbuffer,int* pibuf,int* pbuflen,
+						int c,
+						int bufblk){
+
+/*  add the specified character to the token buffer  */
+
+	char*   buffer2=NULL;
+
+/*  check buffer length and realloc if necessary  */
+
+	if (*pibuf+2 > *pbuflen) {
+		*pbuflen+=bufblk;
+		buffer2=xNew<char>(*pbuflen);
+		memcpy(buffer2,*pbuffer,(*pbuflen-bufblk)*sizeof(char));
+		xDelete<char>(*pbuffer);
+		*pbuffer=buffer2;
+		buffer2=NULL;
+//		*pbuffer=(char *) xrealloc(*pbuffer,*pbuflen*sizeof(char));
+	}
+
+/*  add character and terminator  */
+
+	(*pbuffer)[(*pibuf)++]=c;
+	(*pbuffer)[ *pibuf   ]='\0';
+
+	return;
+}
+/*}}}*/
+/*FUNCTION  KMLFileTagName {{{*/
+char* KMLFileTagName(char* pname,
+					 char* ktag){
+
+	return(KMLFileTagName(pname,NULL,0,
+						  ktag));
+}
+/*}}}*/
+/*FUNCTION  KMLFileTagName {{{*/
+char* KMLFileTagName(char* pname,int *m,int maxlen,
+					 char* ktag){
+
+/*  for the given tag buffer, read and store the name  */
+
+	char*   ktagi;
+	char*   ktokn;
+
+	if (strncmp(&ktag[0],"<"        ,1) || strncmp(&ktag[strlen(ktag)-1],">",1))
+		_error_("KMLFileTagName -- Missing tag delimiters in " << ktag << ".\n");
+
+/*  strtok modifies ktag, so work on copy  */
+
+	ktagi=xNew<char>(strlen(ktag)+1);
+	memcpy(ktagi,ktag,(strlen(ktag)+1)*sizeof(char));
+
+/*  skip opening delimeter and find subsequent blank or closing delimiter  */
+
+	ktokn=strtok(ktagi,"< >");
+//	_printf0_("KMLFileTagName -- initial token=\"" << ktokn << "\".\n");
+
+	if (!pname) {
+		if (maxlen)
+			pname=xNew<char>(maxlen       +1);
+		else
+			pname=xNew<char>(strlen(ktokn)+1);
+	}
+
+	if (maxlen && (maxlen < strlen(ktokn))) {
+		_printf0_("KMLFileTagName -- string field too short for " << ktag << ".\n");
+		_printf0_("KMLFileTagName -- \"" << ktokn << "\" truncated to " << maxlen << " characters.\n");
+		strncpy(pname,ktokn,maxlen);
+	}
+	else
+		memcpy(pname,ktokn,(strlen(ktokn)+1)*sizeof(char));
+
+	xDelete<char>(ktagi);
+
+	if (m)
+		*m=strlen(pname);
+
+	return(pname);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTagAttrib {{{*/
+int KMLFileTagAttrib(KML_Object* kobj,
+					 char* ktag){
+
+/*  for the given tag buffer, read and store the attributes  */
+
+	char*   ktagi;
+	char*   ktokn;
+	char*   ktokv;
+	char    quote[]={'\"','\0'};
+	int     isolo=0;
+
+/*  strtok modifies ktag, so work on copy  */
+
+	ktagi=xNew<char>(strlen(ktag)+1);
+	memcpy(ktagi,ktag,(strlen(ktag)+1)*sizeof(char));
+
+/*  loop through tag to find all attributes  */
+
+	/*  return first non blank and move past subsequent blank  */
+	ktokn=strtok(ktagi," ");
+//	_printf0_("KMLFileTagAttrib -- initial token=\"" << ktokn << "\".\n");
+
+	/*  return next non " =?/>" and move past subsequent " =?/>"  */
+	while (ktokn=strtok(NULL," =?/>")) {
+
+		/*  return next non quote and move past subsequent quote  */
+		ktokv=strtok(NULL,quote);
+//		_printf0_("KMLFileTagAttrib -- attribute " << ktokn << "=\"" << ktokv << "\".\n");
+
+/*  add the attribute to the dataset  */
+
+		if (kobj)
+			kobj->AddAttrib(ktokn,ktokv);
+	}
+
+	xDelete<char>(ktagi);
+
+/*  check for xml declaration, dtd declaration, or solo tag  */
+
+	if ((!strncmp(&ktag[0],"<?"       ,2) && !strncmp(&ktag[strlen(ktag)-2],"?>",2)) ||
+		(!strncmp(&ktag[0],"<!DOCTYPE",9) && !strncmp(&ktag[strlen(ktag)-1], ">",1)) ||
+		(!strncmp(&ktag[0],"<"        ,1) && !strncmp(&ktag[strlen(ktag)-2],"/>",2)))
+		isolo=1;
+//	_printf0_("KMLFileTagAttrib -- isolo=" << isolo << ".\n");
+
+	return(isolo);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+int KMLFileTokenParse(int* pival,
+					  char* ktag,
+					  FILE* fid){
+
+	char*   kstr;
+
+/*  get next token and convert to appropriate format  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
+
+	sscanf(kstr,"%d",pival);
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=" << *pival << ".\n");
+
+	return(0);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+int KMLFileTokenParse(bool* pbval, char* ktag, FILE* fid){
+
+	int     ival;
+	char*   kstr;
+
+/*  get next token and convert to appropriate format  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+	  {_error_("KMLFileTokenParse -- Missing bool field for " << ktag << ".\n");}
+
+	sscanf(kstr,"%d",&ival);
+	*pbval=(bool)ival;
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=" << (*pbval ? "true" : "false") << ".\n");
+
+	return(0);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+char* KMLFileTokenParse(char* pstr,
+						char* ktag,
+						FILE* fid){
+
+	return(KMLFileTokenParse(pstr,NULL,0,
+							 ktag,
+							 fid));
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+char* KMLFileTokenParse(char* pstr,int *m,int maxlen,
+						char* ktag,
+						FILE* fid){
+
+	char*   kstr;
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing string field for " << ktag << ".\n");
+
+	if (!pstr) {
+		if (maxlen)
+			pstr=xNew<char>(maxlen      +1);
+		else
+			pstr=xNew<char>(strlen(kstr)+1);
+	}
+
+	if (maxlen && (maxlen < strlen(kstr))) {
+		_printf0_("KMLFileTokenParse -- string field too short for " << ktag << ".\n");
+		_printf0_("KMLFileTokenParse -- \"" << kstr << "\" truncated to " << maxlen << " characters.\n");
+		strncpy(pstr,kstr,maxlen);
+	}
+	else
+		memcpy(pstr,kstr,(strlen(kstr)+1)*sizeof(char));
+
+	xDelete<char>(kstr);
+
+	if (m)
+		*m=strlen(pstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=\"" << pstr << "\".\n");
+
+	return(pstr);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+int KMLFileTokenParse(float* pfval,
+					  char* ktag,
+					  FILE* fid){
+
+	char*   kstr;
+
+/*  get next token and convert to appropriate format  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+	  {_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");}
+
+	sscanf(kstr,"%g",pfval);
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=" << *pfval << ".\n");
+
+	return(0);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+int KMLFileTokenParse(double* pdval,
+					  char* ktag,
+					  FILE* fid){
+
+	char*   kstr;
+
+/*  get next token and convert to appropriate format  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
+
+	sscanf(kstr,"%lg",pdval);
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=" << *pdval << ".\n");
+
+	return(0);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+int KMLFileTokenParse(double **pdval,int* m,int maxlen,
+					  char* ktag,
+					  FILE* fid){
+
+	int     i=-1;
+	char*   kstr;
+	char*   ktok;
+	double* dval2=NULL;
+	char    delim[]={' ',',','\f','\n','\r','\t','\v','\0'};
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing double [m] field for " << ktag << ".\n");
+
+	if (!*pdval)
+		if (maxlen)
+			*pdval=xNew<IssmDouble>(maxlen            );
+		else
+			*pdval=xNew<IssmDouble>((strlen(kstr)+1)/2);
+
+/*  loop through string to get all values  */
+
+	ktok=strtok(kstr,delim);
+	while (ktok) {
+		i++;
+		if (maxlen && (maxlen < i+1))
+			_error_("KMLFileTokenParse -- Double [m] field too short for " << ktag << ".\n");
+		sscanf(ktok,"%lg",&((*pdval)[i]));
+		ktok=strtok(NULL,delim);
+	}
+	xDelete<char>(kstr);
+
+	if (!maxlen)
+		dval2=xNew<double>(i+1);
+		memcpy(dval2,*pdval,(i+1)*sizeof(double));
+		xDelete<double>(*pdval);
+		*pdval=dval2;
+		dval2=NULL;
+//		*pdval=(double *) xrealloc(*pdval,(i+1)*sizeof(double));
+
+	if (m)
+		*m=i+1;
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=...\n");
+//	for (j=0; j<=i; j++)
+//		_printf0_("   [" << j << "]: " << (*pdval)[j] << "g\n");
+
+	return(0);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+int KMLFileTokenParse(double **pdval,int* m,int n,int maxlen,
+					  char* ktag,
+					  FILE* fid){
+
+	int     i=-1,j=-1;
+	char*   kstr;
+	char*   ktok;
+	double* dval2=NULL;
+	char    delim[]={' ',',','\f','\n','\r','\t','\v','\0'};
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing double [m x n] field for " << ktag << ".\n");
+
+	if (!*pdval)
+		if (maxlen)
+			*pdval=xNew<IssmDouble>(maxlen*n          );
+		else
+			*pdval=xNew<IssmDouble>((strlen(kstr)+1)/2);
+
+/*  loop through string to get all values  */
+
+	ktok=strtok(kstr,delim);
+	while (ktok) {
+		i++;
+		if (maxlen && (maxlen*n < i+1))
+			_error_("KMLFileTokenParse -- Double [m x n] field too short for " << ktag << ".\n");
+		j=(j+1) % n;
+		sscanf(ktok,"%lg",&((*pdval)[i]));
+		ktok=strtok(NULL,delim);
+	}
+	xDelete<char>(kstr);
+
+	if (!maxlen)
+		dval2=xNew<double>((i+1)*n);
+		memcpy(dval2,*pdval,((i+1)*n)*sizeof(double));
+		xDelete<double>(*pdval);
+		*pdval=dval2;
+		dval2=NULL;
+//		*pdval=(double *) xrealloc(*pdval,((i+1)*n)*sizeof(double));
+
+	if (m)
+		*m=((i+1)+(n-1))/n;
+
+	if ((i+1) % n)
+		_printf0_("KMLFileTokenParse -- Double [m x n] field for " << ktag << " does not have multiple of n values.\n");
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_printf0_("KMLFileTokenParse -- " << ktag << "=...\n");
+//	for (j=0; j<=i; j++)
+//		_printf0_("   [" << j << "]: " << (*pdval)[j] << "g\n");
+
+	return(0);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTagSkip {{{*/
+int KMLFileTagSkip(char* ktag,
+				   FILE* fid){
+
+	char*   kstr;
+
+/*  note that tags of the same type can be nested inside each other, so for each
+	opening tag, must find corresponding closing tag  */
+
+	_printf0_("KMLFileTagSkip -- input tag " << ktag << ".\n");
+
+/*  if next token is a closing tag, compare to input  */
+
+	while (kstr=KMLFileToken(fid,
+							 NULL,NULL)) {
+		if      ((kstr[0] == '<') &&
+				 (kstr[1] == '/') &&
+				 (!strncmp(&(kstr[2]),&(ktag[1]),(strcspn(ktag," >")-1)/sizeof(char)))) {
+			_printf0_("KMLFileTagSkip -- closing tag " << kstr << ".\n");
+			xDelete<char>(kstr);
+			return(0);
+		}
+
+/*  if next token is an opening tag, call recursively  */
+
+		else if ((kstr[0] == '<') &&
+				 (kstr[1] != '/')) {
+			_printf0_("KMLFileTagSkip -- opening tag " << kstr << ".\n");
+			KMLFileTagSkip(kstr,
+						   fid);
+		}
+
+/*  if next token is a closing tag, error out  */
+
+		else if ((kstr[0] == '<') &&
+				 (kstr[1] == '/')) {
+			_error_("KMLFileTagSkip -- Unexpected closing tag " << kstr << ".\n");
+		}
+
+		xDelete<char>(kstr);
+	}
+
+	_error_("KMLFileTokenParse -- Corresponding closing tag for " << ktag << " not found.\n");
+
+	return(0);
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KMLFileReadUtils.h
===================================================================
--- /issm/trunk/src/c/kml/KMLFileReadUtils.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KMLFileReadUtils.h	(revision 15396)
@@ -0,0 +1,31 @@
+/*!\file:  KMLFileReadUtils.h
+ * \brief: header file for kml file reading utilities.
+ */ 
+
+#ifndef _KMLFILEREADUTILS_H
+#define _KMLFILEREADUTILS_H
+
+/*Headers:{{{*/
+#include "../shared/shared.h"
+#include "../datastructures/datastructures.h"
+class KML_Object;
+/*}}}*/
+
+/* local prototypes: */
+char* KMLFileToken(FILE* fid, int* pncom,char*** ppcom);
+char* KMLFileTokenComment(FILE* fid);
+void KMLFileTokenBuffer(char** pbuffer,int* pibuf,int* pbuflen, int c, int bufblk);
+char* KMLFileTagName(char* pname, char* ktag);
+char* KMLFileTagName(char* pname,int *m,int maxlen, char* ktag);
+int KMLFileTagAttrib(KML_Object* kobj, char* ktag);
+int KMLFileTokenParse(int* pival, char* ktag, FILE* fid);
+int KMLFileTokenParse(bool* pbval, char* ktag, FILE* fid);
+char* KMLFileTokenParse(char* pstr, char* ktag, FILE* fid);
+char* KMLFileTokenParse(char* pstr,int *m,int maxlen, char* ktag, FILE* fid);
+int KMLFileTokenParse(float* pfval, char* ktag, FILE* fid);
+int KMLFileTokenParse(double* pdval, char* ktag, FILE* fid);
+int KMLFileTokenParse(double **pdval,int* m,int maxlen, char* ktag, FILE* fid);
+int KMLFileTokenParse(double **pdval,int* m,int n,int maxlen, char* ktag, FILE* fid);
+int KMLFileTagSkip(char* ktag, FILE* fid);
+
+#endif  /* _KMLFILEREADUTILS_H */
Index: /issm/trunk/src/c/kml/KML_Attribute.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Attribute.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Attribute.cpp	(revision 15396)
@@ -0,0 +1,128 @@
+/*!\file KML_Attribute.cpp
+ * \brief: implementation of the kml_attribute object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Attribute.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Attribute::KML_Attribute(){{{*/
+KML_Attribute::KML_Attribute(){
+
+	name      =NULL;
+	value     =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::~KML_Attribute(){{{*/
+KML_Attribute::~KML_Attribute(){
+
+	if (name      ) xDelete<char>(name);
+	if (value     ) xDelete<char>(value);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Attribute::Echo {{{*/
+void  KML_Attribute::Echo(){
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _printf0_("    ");
+	for (i=0;i<10-strlen(name);i++)
+		if(flag) _printf0_(" ");
+	if(flag) _printf0_(name << ": \"" << value << "\"\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::DeepEcho {{{*/
+void  KML_Attribute::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Attribute::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::DeepEcho {{{*/
+void  KML_Attribute::DeepEcho(const char* indent){
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "    ");
+	for (i=0;i<10-strlen(name);i++)
+		if(flag) _printf0_(" ");
+	if(flag) _printf0_(name << ": \"" << value << "\"\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Write {{{*/
+void  KML_Attribute::Write(FILE* filout,const char* indent){
+
+//  attributes always written in keyword line of kml_object
+
+	fprintf(filout,"%s%s=\"%s\"",indent,name,value);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Read {{{*/
+void  KML_Attribute::Read(FILE* fid,char* kstr){
+
+//  attributes always read in keyword line of kml_object
+
+	;
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Alloc {{{*/
+void  KML_Attribute::Alloc(const char* namei,const char* valuei){
+
+	name =xNew<char>(strlen(namei )+1);
+	memcpy(name,namei,(strlen(namei)+1)*sizeof(char));
+
+	value=xNew<char>(strlen(valuei)+1);
+	memcpy(value,valuei,(strlen(valuei)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Add {{{*/
+void  KML_Attribute::Add(DataSet* attrib){
+
+	attrib->AddObject((Object*)this);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Get {{{*/
+void  KML_Attribute::Get(char** pvalueo,char* deflt){
+
+	if (!value || !strlen(value)) {
+		*pvalueo=xNew<char>(strlen(deflt)+1);
+		memcpy(*pvalueo,deflt,(strlen(deflt)+1)*sizeof(char));
+	}
+	else {
+		*pvalueo=xNew<char>(strlen(value)+1);
+		memcpy(*pvalueo,value,(strlen(value)+1)*sizeof(char));
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Attribute.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Attribute.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Attribute.h	(revision 15396)
@@ -0,0 +1,41 @@
+/*! \file KML_Attribute.h 
+ *  \brief: header file for kml_attribute object
+ */
+
+#ifndef _KML_ATTRIBUTE_H_
+#define _KML_ATTRIBUTE_H_
+
+/*Headers:{{{*/
+#include "../shared/shared.h"
+#include "../datastructures/datastructures.h"
+/*}}}*/
+
+class KML_Attribute: public Object {
+
+	public:
+
+		char* name;
+		char* value;
+
+		/*KML_Attribute constructors, destructors {{{*/
+		KML_Attribute();
+		~KML_Attribute();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(const char* indent);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  Alloc(const char* namei,const char* valuei);
+		void  Add(DataSet* attrib);
+		void  Get(char** pvalueo,char* deflt);
+
+};
+#endif  /* _KML_ATTRIBUTE_H */
Index: /issm/trunk/src/c/kml/KML_ColorStyle.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_ColorStyle.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_ColorStyle.cpp	(revision 15396)
@@ -0,0 +1,106 @@
+/*!\file KML_ColorStyle.cpp
+ * \brief: implementation of the kml_colorstyle abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_ColorStyle.h"
+#include "./KML_SubStyle.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_ColorStyle::KML_ColorStyle(){{{*/
+KML_ColorStyle::KML_ColorStyle(){
+
+	strcpy(color     ,"ffffffff");
+	strcpy(colormode ,"normal");
+
+}
+/*}}}*/
+/*FUNCTION KML_ColorStyle::~KML_ColorStyle(){{{*/
+KML_ColorStyle::~KML_ColorStyle(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_ColorStyle::Echo {{{*/
+void  KML_ColorStyle::Echo(){
+
+	bool  flag=true;
+
+	KML_SubStyle::Echo();
+
+	if(flag) _printf0_("         color: " << color << "\n");
+	if(flag) _printf0_("     colormode: " << colormode << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_ColorStyle::DeepEcho {{{*/
+void  KML_ColorStyle::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_ColorStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_ColorStyle::DeepEcho {{{*/
+void  KML_ColorStyle::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	KML_SubStyle::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "         color: " << color << "\n");
+	if(flag) _printf0_(indent << "     colormode: " << colormode << "\n");
+}
+/*}}}*/
+/*FUNCTION KML_ColorStyle::Write {{{*/
+void  KML_ColorStyle::Write(FILE* filout,const char* indent){
+
+	KML_SubStyle::Write(filout,indent);
+
+	if (color     && strlen(color))
+		fprintf(filout,"%s  <color>%s</color>\n",indent,color);
+	if (colormode && strlen(colormode))
+		fprintf(filout,"%s  <colorMode>%s</colorMode>\n",indent,colormode);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_ColorStyle::Read {{{*/
+void  KML_ColorStyle::Read(FILE* fid,char* kstr){
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</ColorStyle",12))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_ColorStyle::Read -- Unexpected closing tag " << kstr);}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_ColorStyle::Read -- Unexpected field \"" << kstr << "\"");}
+
+	else if (!strcmp(kstr,"<color>"))
+		KMLFileTokenParse( color     ,NULL,KML_COLORSTYLE_COLOR_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<colorMode>"))
+		KMLFileTokenParse( colormode ,NULL,KML_COLORSTYLE_COLORMODE_LENGTH, kstr, fid);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_SubStyle::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_ColorStyle.h
===================================================================
--- /issm/trunk/src/c/kml/KML_ColorStyle.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_ColorStyle.h	(revision 15396)
@@ -0,0 +1,41 @@
+/*! \file KML_ColorStyle.h 
+ *  \brief: header file for kml_colorstyle abstract object
+ */
+
+#ifndef _KML_COLORSTYLE_H_
+#define _KML_COLORSTYLE_H_
+
+#define KML_COLORSTYLE_COLOR_LENGTH      8
+#define KML_COLORSTYLE_COLORMODE_LENGTH  6
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_SubStyle.h"
+/*}}}*/
+
+class KML_ColorStyle: public KML_SubStyle {
+
+	public:
+
+		char  color[KML_COLORSTYLE_COLOR_LENGTH+1];
+		char  colormode[KML_COLORSTYLE_COLORMODE_LENGTH+1];
+
+		/*KML_ColorStyle constructors, destructors {{{*/
+		KML_ColorStyle();
+		~KML_ColorStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_COLORSTYLE_H */
Index: /issm/trunk/src/c/kml/KML_Comment.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Comment.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Comment.cpp	(revision 15396)
@@ -0,0 +1,113 @@
+/*!\file KML_Comment.cpp
+ * \brief: implementation of the kml_comment object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Comment.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Comment::KML_Comment(){{{*/
+KML_Comment::KML_Comment(){
+
+	value     =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_Comment::~KML_Comment(){{{*/
+KML_Comment::~KML_Comment(){
+
+	if (value     ) xDelete<char>(value);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Comment::Echo {{{*/
+void  KML_Comment::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("    ");
+	if(flag) _printf0_(value << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::DeepEcho {{{*/
+void  KML_Comment::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Comment::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::DeepEcho {{{*/
+void  KML_Comment::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "    ");
+	if(flag) _printf0_(value << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Write {{{*/
+void  KML_Comment::Write(FILE* filout,const char* indent){
+
+	if (strncmp(&value[0]              ,"<!--",4))
+		fprintf(filout,"%s<!--\n",indent);
+	fprintf(filout,"%s  %s\n",indent,value);
+	if (strncmp(&value[strlen(value)-3],"-->" ,3))
+		fprintf(filout,"%s-->\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Read {{{*/
+void  KML_Comment::Read(FILE* fid,char* kstr){
+
+//  comments always read as part of KMLFileToken
+
+	;
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Alloc {{{*/
+void  KML_Comment::Alloc(const char* valuei){
+
+	value=xNew<char>(strlen(valuei)+1);
+	memcpy(value,valuei,(strlen(valuei)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Add {{{*/
+void  KML_Comment::Add(DataSet* commnt){
+
+	commnt->AddObject((Object*)this);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Get {{{*/
+void  KML_Comment::Get(char** pvalueo){
+
+	*pvalueo=xNew<char>(strlen(value)+1);
+	memcpy(*pvalueo,value,(strlen(value)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Comment.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Comment.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Comment.h	(revision 15396)
@@ -0,0 +1,42 @@
+/*! \file KML_Comment.h 
+ *  \brief: header file for kml_comment object
+ */
+
+#ifndef _KML_COMMENT_H_
+#define _KML_COMMENT_H_
+
+/*Headers:{{{*/
+#include "../shared/shared.h"
+#include "../datastructures/datastructures.h"
+class DataSet;
+/*}}}*/
+
+class KML_Comment: public Object {
+
+	public:
+
+		char* name;
+		char* value;
+
+		/*KML_Comment constructors, destructors {{{*/
+		KML_Comment();
+		~KML_Comment();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(const char* indent);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  Alloc(const char* valuei);
+		void  Add(DataSet* commnt);
+		void  Get(char** pvalueo);
+
+};
+#endif  /* _KML_COMMENT_H */
Index: /issm/trunk/src/c/kml/KML_Container.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Container.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Container.cpp	(revision 15396)
@@ -0,0 +1,168 @@
+/*!\file KML_Container.cpp
+ * \brief: implementation of the kml_container abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Placemark.h"
+#include "./KML_Document.h"
+#include "./KML_GroundOverlay.h"
+#include "./KML_Folder.h"
+#include "./KML_Object.h"
+#include "./KML_Container.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Container::KML_Container(){{{*/
+KML_Container::KML_Container(){
+
+	feature   =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_Container::~KML_Container(){{{*/
+KML_Container::~KML_Container(){
+
+	if (feature) {
+		delete feature;
+		feature   =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Container::Echo {{{*/
+void  KML_Container::Echo(){
+
+	bool  flag=true;
+
+	KML_Feature::Echo();
+
+	if(flag) _printf0_("       feature: (size=" << feature->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::DeepEcho {{{*/
+void  KML_Container::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Container::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::DeepEcho {{{*/
+void  KML_Container::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	KML_Feature::DeepEcho(indent);
+
+/*  loop over the features for the container  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (feature->Size())
+		for (i=0; i<feature->Size(); i++) {
+			if(flag) _printf0_(indent << "       feature: -------- begin [" << i << "] --------\n");
+			((KML_Feature *)feature->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "       feature: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "       feature: [empty]\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::Write {{{*/
+void  KML_Container::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent2[81];
+
+	KML_Feature::Write(filout,indent);
+
+/*  loop over the features for the container  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	for (i=0; i<feature->Size(); i++)
+		((KML_Feature *)feature->GetObjectByOffset(i))->Write(filout,indent2);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::Read {{{*/
+void  KML_Container::Read(FILE* fid,char* kstr){
+
+	KML_Object*  kobj;
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Container",11)) {
+		xDelete<char>(kstr);
+		return;
+	}
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Container::Read -- Unexpected closing tag " << kstr );}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Container::Read -- Unexpected field \"" << kstr << "\"");}
+
+	else if (!strncmp(kstr,"<Placemark",10)) {
+		kobj=(KML_Object*)new KML_Placemark();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Folder", 7)) {
+		kobj=(KML_Object*)new KML_Folder();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Document", 9)) {
+		kobj=(KML_Object*)new KML_Document();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<GroundOverlay",14)) {
+		kobj=(KML_Object*)new KML_GroundOverlay();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Feature::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::WriteExp {{{*/
+void  KML_Container::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+
+/*  loop over the features for the container  */
+
+	for (i=0; i<feature->Size(); i++)
+		((KML_Object *)feature->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Container.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Container.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Container.h	(revision 15396)
@@ -0,0 +1,38 @@
+/*! \file KML_Container.h 
+ *  \brief: header file for kml_container abstract object
+ */
+
+#ifndef _KML_CONTAINER_H_
+#define _KML_CONTAINER_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Feature.h"
+class DataSet;
+/*}}}*/
+
+class KML_Container: public KML_Feature {
+
+	public:
+
+		DataSet* feature;
+
+		/*KML_Container constructors, destructors {{{*/
+		KML_Container();
+		~KML_Container();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_CONTAINER_H */
Index: /issm/trunk/src/c/kml/KML_Document.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Document.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Document.cpp	(revision 15396)
@@ -0,0 +1,122 @@
+/*!\file KML_Document.cpp
+ * \brief: implementation of the kml_document object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Document.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Document::KML_Document(){{{*/
+KML_Document::KML_Document(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_Document::~KML_Document(){{{*/
+KML_Document::~KML_Document(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Document::Echo {{{*/
+void  KML_Document::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Document:\n");
+	KML_Container::Echo();
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Document::DeepEcho {{{*/
+void  KML_Document::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Document::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Document::DeepEcho {{{*/
+void  KML_Document::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Document:\n");
+	KML_Container::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Document::Write {{{*/
+void  KML_Document::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<Document",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Container::Write(filout,indent);
+
+	fprintf(filout,"%s</Document>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Document::Read {{{*/
+void  KML_Document::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Document",10)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Document::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Document::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Container::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Document.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Document.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Document.h	(revision 15396)
@@ -0,0 +1,35 @@
+/*! \file KML_Document.h 
+ *  \brief: header file for kml_document object
+ */
+
+#ifndef _KML_DOCUMENT_H_
+#define _KML_DOCUMENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Container.h"
+class KML_Feature;
+/*}}}*/
+
+class KML_Document: public KML_Container {
+
+	public:
+
+		/*KML_Document constructors, destructors {{{*/
+		KML_Document();
+		~KML_Document();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_DOCUMENT_H */
Index: /issm/trunk/src/c/kml/KML_Feature.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Feature.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Feature.cpp	(revision 15396)
@@ -0,0 +1,185 @@
+/*!\file KML_Feature.cpp
+ * \brief: implementation of the kml_feature abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../shared/shared.h"
+/*}}}*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Feature.h"
+#include "./KML_Style.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Feature::KML_Feature(){{{*/
+KML_Feature::KML_Feature(){
+
+	memcpy(name,"",(strlen("")+1)*sizeof(char));
+
+	visibility=true;
+	open      =false;
+	memcpy(snippet,"",(strlen("")+1)*sizeof(char));
+	memcpy(descript,"",(strlen("")+1)*sizeof(char));
+	memcpy(styleurl,"",(strlen("")+1)*sizeof(char));
+	style     =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_Feature::~KML_Feature(){{{*/
+KML_Feature::~KML_Feature(){
+
+	if (style) {
+		delete style;
+		style     =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Feature::Echo {{{*/
+void  KML_Feature::Echo(){
+
+	bool  flag=true;
+
+	KML_Object::Echo();
+
+	if(flag) _printf0_("          name: \"" << name << "\"\n");
+	if(flag) _printf0_("    visibility: " << (visibility ? "true" : "false") << "\n");
+	if(flag) _printf0_("          open: " << (open ? "true" : "false") << "\n");
+	if(flag) _printf0_("       snippet: \"" << snippet << "\"\n");
+	if(flag) _printf0_("      descript: \"" << descript << "\"\n");
+	if(flag) _printf0_("      styleurl: \"" << styleurl << "\"\n");
+	if(flag) _printf0_("         style: (size=" << style->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Feature::DeepEcho {{{*/
+void  KML_Feature::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Feature::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Feature::DeepEcho {{{*/
+void  KML_Feature::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	KML_Object::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "          name: \"" << name << "\"\n");
+	if(flag) _printf0_(indent << "    visibility: " << (visibility ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "          open: " << (open ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "       snippet: \"" << snippet << "\"\n");
+	if(flag) _printf0_(indent << "      descript: \"" << descript << "\"\n");
+	if(flag) _printf0_(indent << "      styleurl: \"" << styleurl << "\"\n");
+
+/*  loop over any styles for the feature  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (style->Size())
+		for (i=0; i<style->Size(); i++) {
+			if(flag) _printf0_(indent << "         style: -------- begin [" << i << "] --------\n");
+			((KML_Style *)style->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "         style: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "         style: [empty]\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Feature::Write {{{*/
+void  KML_Feature::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent2[81];
+
+	KML_Object::Write(filout,indent);
+
+	if (name     && strlen(name))
+		fprintf(filout,"%s  <name>%s</name>\n",indent,name);
+	fprintf(filout,"%s  <visibility>%d</visibility>\n",indent,(visibility ? 1 : 0));
+	fprintf(filout,"%s  <open>%d</open>\n",indent,(open ? 1 : 0));
+	if (snippet  && strlen(snippet))
+		fprintf(filout,"%s  <Snippet maxLines=\"2\">%s</Snippet>\n",indent,snippet);
+	if (descript && strlen(descript))
+		fprintf(filout,"%s  <description>%s</description>\n",indent,descript);
+	if (styleurl && strlen(styleurl))
+		fprintf(filout,"%s  <styleUrl>%s</styleUrl>\n",indent,styleurl);
+
+/*  loop over any styles for the feature  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+    for (i=0; i<style->Size(); i++)
+        ((KML_Style *)style->GetObjectByOffset(i))->Write(filout,indent2);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Feature::Read {{{*/
+void  KML_Feature::Read(FILE* fid,char* kstr){
+
+	KML_Object*  kobj;
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Feature", 9))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Feature::Read -- Unexpected closing tag " << kstr);}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Feature::Read -- Unexpected field \"" << kstr << "\"");}
+
+	else if (!strncmp(kstr,"<Style", 6)) {
+		kobj=(KML_Object*)new KML_Style();
+		kobj->Read(fid,kstr);
+		style     ->AddObject((Object*)kobj);
+	}
+
+	else if (!strcmp(kstr,"<name>"))
+		KMLFileTokenParse( name      ,NULL,KML_FEATURE_NAME_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<visibility>"))
+		KMLFileTokenParse(&visibility, kstr, fid);
+	else if (!strcmp(kstr,"<open>"))
+		KMLFileTokenParse(&open      , kstr, fid);
+	else if (!strncmp(kstr,"<snippet", 8))
+		KMLFileTokenParse( snippet   ,NULL,KML_FEATURE_SNIPPET_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<description>"))
+		KMLFileTokenParse( descript  ,NULL,KML_FEATURE_DESCRIPT_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<styleUrl>"))
+		KMLFileTokenParse( styleurl  ,NULL,KML_FEATURE_STYLEURL_LENGTH, kstr, fid);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Feature.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Feature.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Feature.h	(revision 15396)
@@ -0,0 +1,49 @@
+/*! \file KML_Feature.h 
+ *  \brief: header file for kml_feature abstract object
+ */
+
+#ifndef _KML_FEATURE_H_
+#define _KML_FEATURE_H_
+
+#define KML_FEATURE_NAME_LENGTH         80
+#define KML_FEATURE_SNIPPET_LENGTH     160
+#define KML_FEATURE_DESCRIPT_LENGTH   3200
+#define KML_FEATURE_STYLEURL_LENGTH     80
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+class KML_Style;
+class DataSet;
+/*}}}*/
+
+class KML_Feature: public KML_Object {
+
+	public:
+
+		char  name[KML_FEATURE_NAME_LENGTH+1];
+		bool  visibility;
+		bool  open;
+		char  snippet[KML_FEATURE_SNIPPET_LENGTH+1];
+		char  descript[KML_FEATURE_DESCRIPT_LENGTH+1];
+		char  styleurl[KML_FEATURE_STYLEURL_LENGTH+1];
+		DataSet* style;
+
+		/*KML_Feature constructors, destructors {{{*/
+		KML_Feature();
+		~KML_Feature();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FEATURE_H */
Index: /issm/trunk/src/c/kml/KML_File.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_File.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_File.cpp	(revision 15396)
@@ -0,0 +1,136 @@
+/*!\file KML_File.cpp
+ * \brief: implementation of the kml_file object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_File.h" 
+#include "./KML_Object.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_File::KML_File(){{{*/
+KML_File::KML_File(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_File::~KML_File(){{{*/
+KML_File::~KML_File(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_File::Echo {{{*/
+void  KML_File::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_File:\n");
+	KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::DeepEcho {{{*/
+void  KML_File::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_File::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::DeepEcho {{{*/
+void  KML_File::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_File:\n");
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::Write {{{*/
+void  KML_File::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<kml",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Object::Write(filout,indent);
+
+	fprintf(filout,"%s</kml>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::Read {{{*/
+void  KML_File::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</kml", 5)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_File::Read -- Unexpected closing tag " << kstri << ".");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_File::Read -- Unexpected field \"" << kstri << "\"");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::WriteExp {{{*/
+void  KML_File::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+
+/*  loop over the kml objects for the file  */
+
+	for (i=0; i<kmlobj->Size(); i++)
+		((KML_Object *)kmlobj->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_File.h
===================================================================
--- /issm/trunk/src/c/kml/KML_File.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_File.h	(revision 15396)
@@ -0,0 +1,37 @@
+/*! \file KML_File.h 
+ *  \brief: header file for kml_file object
+ */
+
+#ifndef _KML_FILE_H_
+#define _KML_FILE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+
+#include "./KML_Feature.h"
+class DataSet;
+/*}}}*/
+
+class KML_File: public KML_Object {
+
+	public:
+
+		/*KML_File constructors, destructors {{{*/
+		KML_File();
+		~KML_File();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FILE_H */
Index: /issm/trunk/src/c/kml/KML_Folder.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Folder.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Folder.cpp	(revision 15396)
@@ -0,0 +1,122 @@
+/*!\file KML_Folder.cpp
+ * \brief: implementation of the kml_folder object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Folder.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Folder::KML_Folder(){{{*/
+KML_Folder::KML_Folder(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_Folder::~KML_Folder(){{{*/
+KML_Folder::~KML_Folder(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Folder::Echo {{{*/
+void  KML_Folder::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Folder:\n");
+	KML_Container::Echo();
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Folder::DeepEcho {{{*/
+void  KML_Folder::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Folder::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Folder::DeepEcho {{{*/
+void  KML_Folder::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Folder:\n");
+	KML_Container::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Folder::Write {{{*/
+void  KML_Folder::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<Folder",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Container::Write(filout,indent);
+
+	fprintf(filout,"%s</Folder>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Folder::Read {{{*/
+void  KML_Folder::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Folder", 8)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Folder::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Folder::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Container::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Folder.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Folder.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Folder.h	(revision 15396)
@@ -0,0 +1,35 @@
+/*! \file KML_Folder.h 
+ *  \brief: header file for kml_folder object
+ */
+
+#ifndef _KML_FOLDER_H_
+#define _KML_FOLDER_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Container.h"
+class KML_Feature;
+/*}}}*/
+
+class KML_Folder: public KML_Container {
+
+	public:
+
+		/*KML_Folder constructors, destructors {{{*/
+		KML_Folder();
+		~KML_Folder();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FOLDER_H */
Index: /issm/trunk/src/c/kml/KML_Geometry.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Geometry.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Geometry.cpp	(revision 15396)
@@ -0,0 +1,86 @@
+/*!\file KML_Geometry.cpp
+ * \brief: implementation of the kml_geometry abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Geometry.h"
+#include "./KML_Object.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Geometry::KML_Geometry(){{{*/
+KML_Geometry::KML_Geometry(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_Geometry::~KML_Geometry(){{{*/
+KML_Geometry::~KML_Geometry(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Geometry::Echo {{{*/
+void  KML_Geometry::Echo(){
+
+	this->KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Geometry::DeepEcho {{{*/
+void  KML_Geometry::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Geometry::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Geometry::DeepEcho {{{*/
+void  KML_Geometry::DeepEcho(const char* indent){
+
+	this->KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Geometry::Write {{{*/
+void  KML_Geometry::Write(FILE* filout,const char* indent){
+
+	KML_Object::Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Geometry::Read {{{*/
+void  KML_Geometry::Read(FILE* fid,char* kstr){
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Geometry",10))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Geometry::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Geometry::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Geometry.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Geometry.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Geometry.h	(revision 15396)
@@ -0,0 +1,34 @@
+/*! \file KML_Geometry.h 
+ *  \brief: header file for kml_geometry abstract object
+ */
+
+#ifndef _KML_GEOMETRY_H_
+#define _KML_GEOMETRY_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_Geometry: public KML_Object {
+
+	public:
+
+		/*KML_Geometry constructors, destructors {{{*/
+		KML_Geometry();
+		~KML_Geometry();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_GEOMETRY_H */
Index: /issm/trunk/src/c/kml/KML_GroundOverlay.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_GroundOverlay.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_GroundOverlay.cpp	(revision 15396)
@@ -0,0 +1,162 @@
+/*!\file KML_GroundOverlay.cpp
+ * \brief: implementation of the kml_groundoverlay object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Object.h"
+#include "./KML_LatLonBox.h"
+#include "./KML_GroundOverlay.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_GroundOverlay::KML_GroundOverlay(){{{*/
+KML_GroundOverlay::KML_GroundOverlay(){
+
+	altitude  = 0.;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	llbox     =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_GroundOverlay::~KML_GroundOverlay(){{{*/
+KML_GroundOverlay::~KML_GroundOverlay(){
+
+	if (llbox) {
+		delete llbox;
+		llbox     =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_GroundOverlay::Echo {{{*/
+void  KML_GroundOverlay::Echo(){
+
+	_printf_("KML_GroundOverlay:\n");
+	KML_Overlay::Echo();
+
+	_printf_("         altitude: " << altitude << "\n");
+	_printf_("          altmode: " << altmode << "\n");
+	_printf_("            llbox: " << llbox << "\n");
+}
+/*}}}*/
+/*FUNCTION KML_GroundOverlay::DeepEcho {{{*/
+void  KML_GroundOverlay::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_GroundOverlay::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_GroundOverlay::DeepEcho {{{*/
+void  KML_GroundOverlay::DeepEcho(const char* indent){
+
+	char  indent2[81];
+
+	_printf_(indent << "KML_GroundOverlay:\n");
+	KML_Overlay::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	_printf_(indent<<"      altitude: " << altitude << "\n");
+	_printf_(indent<<"       altmode: " << altmode << "\n");
+	if (llbox)
+	 llbox->DeepEcho(indent2);
+	else
+	 _printf_(indent<<"         llbox: " << llbox << "\n");
+}
+/*}}}*/
+/*FUNCTION KML_GroundOverlay::Write {{{*/
+void  KML_GroundOverlay::Write(FILE* filout,const char* indent){
+
+	char  indent2[81];
+
+	fprintf(filout,"%s<GroundOverlay",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Overlay::Write(filout,indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	fprintf(filout,"%s  <altitude>%0.16g</altitude>\n",indent,altitude);
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+	if (llbox)
+		llbox->Write(filout,indent2);
+
+	fprintf(filout,"%s</GroundOverlay>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_GroundOverlay::Read {{{*/
+void  KML_GroundOverlay::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</GroundOverlay",15)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_GroundOverlay::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_GroundOverlay::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<altitude>"))
+			KMLFileTokenParse(&altitude  ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_GROUNDOVERLAY_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strncmp(kstri,"<LatLonBox",10)) {
+			llbox     =new KML_LatLonBox();
+			llbox     ->Read(fid,kstri);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Overlay::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_GroundOverlay.h
===================================================================
--- /issm/trunk/src/c/kml/KML_GroundOverlay.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_GroundOverlay.h	(revision 15396)
@@ -0,0 +1,41 @@
+/*! \file KML_GroundOverlay.h 
+ *  \brief: header file for kml_groundoverlay object
+ */
+
+#ifndef _KML_GROUNDOVERLAY_H_
+#define _KML_GROUNDOVERLAY_H_
+
+#define KML_GROUNDOVERLAY_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Overlay.h"
+class KML_LatLonBox;
+/*}}}*/
+
+class KML_GroundOverlay: public KML_Overlay {
+
+	public:
+
+		double altitude;
+		char  altmode[KML_GROUNDOVERLAY_ALTMODE_LENGTH+1];
+		KML_LatLonBox* llbox;
+
+		/*KML_GroundOverlay constructors, destructors {{{*/
+		KML_GroundOverlay();
+		~KML_GroundOverlay();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_GROUNDOVERLAY_H */
Index: /issm/trunk/src/c/kml/KML_Icon.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Icon.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Icon.cpp	(revision 15396)
@@ -0,0 +1,178 @@
+/*!\file KML_Icon.cpp
+ * \brief: implementation of the kml_feature abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Icon.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Icon::KML_Icon(){{{*/
+KML_Icon::KML_Icon(){
+
+	strcpy(href      ,"");
+	strcpy(refmode   ,"onChange");
+	refint    = 4.;
+	strcpy(vrefmode  ,"never");
+	vreftime  = 4.;
+	vboundsc  = 1.;
+	strcpy(vformat   ,"");
+	strcpy(hquery    ,"");
+
+}
+/*}}}*/
+/*FUNCTION KML_Icon::~KML_Icon(){{{*/
+KML_Icon::~KML_Icon(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Icon::Echo {{{*/
+void  KML_Icon::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Icon:\n");
+	KML_Object::Echo();
+
+	if(flag) _printf0_("          href: \"" << href << "\"\n");
+	if(flag) _printf0_("       refmode: \"" << refmode << "\"\n");
+	if(flag) _printf0_("        refint: " << refint << "\n");
+	if(flag) _printf0_("      vrefmode: \"" << vrefmode << "\"\n");
+	if(flag) _printf0_("      vreftime: " << vreftime << "\n");
+	if(flag) _printf0_("      vboundsc: " << vboundsc << "\n");
+	if(flag) _printf0_("       vformat: \"" << vformat << "\"\n");
+	if(flag) _printf0_("        hquery: \"" << hquery << "\"\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Icon::DeepEcho {{{*/
+void  KML_Icon::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Icon::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Icon::DeepEcho {{{*/
+void  KML_Icon::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Icon:\n");
+	KML_Object::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "          href: \"" << href << "\"\n");
+	if(flag) _printf0_(indent << "       refmode: \"" << refmode << "\"\n");
+	if(flag) _printf0_(indent << "        refint: " << refint << "\n");
+	if(flag) _printf0_(indent << "      vrefmode: \"" << vrefmode << "\"\n");
+	if(flag) _printf0_(indent << "      vreftime: " << vreftime << "\n");
+	if(flag) _printf0_(indent << "      vboundsc: " << vboundsc << "\n");
+	if(flag) _printf0_(indent << "       vformat: \"" << vformat << "\"\n");
+	if(flag) _printf0_(indent << "        hquery: \"" << hquery << "\"\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Icon::Write {{{*/
+void  KML_Icon::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<Icon",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Object::Write(filout,indent);
+
+	if (href     && strlen(href))
+		fprintf(filout,"%s  <href>%s</href>\n",indent,href);
+	if (refmode  && strlen(refmode))
+		fprintf(filout,"%s  <refreshMode>%s</refreshMode>\n",indent,refmode);
+	fprintf(filout,"%s  <refreshInterval>%g</refreshInterval>\n",indent,refint);
+	if (vrefmode && strlen(vrefmode))
+		fprintf(filout,"%s  <viewRefreshMode>%s</viewRefreshMode>\n",indent,vrefmode);
+	fprintf(filout,"%s  <viewRefreshTime>%g</viewRefreshTime>\n",indent,vreftime);
+	fprintf(filout,"%s  <viewBoundScale>%g</viewBoundScale>\n",indent,vboundsc);
+	if (vformat  && strlen(vformat))
+		fprintf(filout,"%s  <viewFormat>%s</viewFormat>\n",indent,vformat);
+	if (hquery   && strlen(hquery))
+		fprintf(filout,"%s  <httpQuery>%s</httpQuery>\n",indent,hquery);
+
+	fprintf(filout,"%s</Icon>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Icon::Read {{{*/
+void  KML_Icon::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Icon", 6)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Icon::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Icon::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<href>"))
+			KMLFileTokenParse( href      ,NULL,KML_ICON_HREF_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<refreshMode>"))
+			KMLFileTokenParse( refmode   ,NULL,KML_ICON_REFMODE_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<refreshInterval>"))
+			KMLFileTokenParse(&refint    , kstri, fid);
+		else if (!strcmp(kstri,"<viewRefreshMode>"))
+			KMLFileTokenParse( vrefmode  ,NULL,KML_ICON_VREFMODE_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<viewRefreshTime>"))
+			KMLFileTokenParse(&vreftime  , kstri, fid);
+		else if (!strcmp(kstri,"<viewBoundScale>"))
+			KMLFileTokenParse(&vboundsc  , kstri, fid);
+		else if (!strcmp(kstri,"<viewFormat>"))
+			KMLFileTokenParse( vformat   ,NULL,KML_ICON_VFORMAT_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<httpQuery>"))
+			KMLFileTokenParse( hquery    ,NULL,KML_ICON_HQUERY_LENGTH, kstri, fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Icon.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Icon.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Icon.h	(revision 15396)
@@ -0,0 +1,49 @@
+/*! \file KML_Icon.h 
+ *  \brief: header file for kml_icon object
+ */
+
+#ifndef _KML_ICON_H_
+#define _KML_ICON_H_
+
+#define KML_ICON_HREF_LENGTH      800
+#define KML_ICON_REFMODE_LENGTH    10
+#define KML_ICON_VREFMODE_LENGTH    9
+#define KML_ICON_VFORMAT_LENGTH   800
+#define KML_ICON_HQUERY_LENGTH    800
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_Icon: public KML_Object {
+
+	public:
+
+		char  href[KML_ICON_HREF_LENGTH+1];
+		char  refmode[KML_ICON_REFMODE_LENGTH+1];
+		float refint;
+		char  vrefmode[KML_ICON_VREFMODE_LENGTH+1];
+		float vreftime;
+		float vboundsc;
+		char  vformat[KML_ICON_VFORMAT_LENGTH+1];
+		char  hquery[KML_ICON_HQUERY_LENGTH+1];
+
+		/*KML_Icon constructors, destructors {{{*/
+		KML_Icon();
+		~KML_Icon();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_ICON_H */
Index: /issm/trunk/src/c/kml/KML_LatLonBox.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_LatLonBox.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_LatLonBox.cpp	(revision 15396)
@@ -0,0 +1,157 @@
+/*!\file KML_LatLonBox.cpp
+ * \brief: implementation of the kml_feature abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_LatLonBox.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_LatLonBox::KML_LatLonBox(){{{*/
+KML_LatLonBox::KML_LatLonBox(){
+
+	north     = 0.;
+	south     = 0.;
+	east      = 0.;
+	west      = 0.;
+	rotation  = 0.;
+
+}
+/*}}}*/
+/*FUNCTION KML_LatLonBox::~KML_LatLonBox(){{{*/
+KML_LatLonBox::~KML_LatLonBox(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_LatLonBox::Echo {{{*/
+void  KML_LatLonBox::Echo(){
+
+	_printf_("KML_LatLonBox:\n");
+	KML_Object::Echo();
+
+	_printf_("         north: " << north << "\n");
+	_printf_("         south: " << south << "\n");
+	_printf_("          east: " << east << "\n");
+	_printf_("          west: " << west << "\n");
+	_printf_("      rotation: " << rotation << "\n");
+}
+/*}}}*/
+/*FUNCTION KML_LatLonBox::DeepEcho {{{*/
+void  KML_LatLonBox::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_LatLonBox::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LatLonBox::DeepEcho {{{*/
+void  KML_LatLonBox::DeepEcho(const char* indent){
+
+	_printf_(indent << "KML_LatLonBox:\n");
+	KML_Object::DeepEcho(indent);
+
+	_printf_("         north: " << north << "\n");
+	_printf_("         south: " << south << "\n");
+	_printf_("          east: " << east << "\n");
+	_printf_("          west: " << west << "\n");
+	_printf_("      rotation: " << rotation << "\n");
+}
+/*}}}*/
+/*FUNCTION KML_LatLonBox::Write {{{*/
+void  KML_LatLonBox::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<LatLonBox",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Object::Write(filout,indent);
+
+	fprintf(filout,"%s  <north>%0.16g</north>\n",indent,north);
+	fprintf(filout,"%s  <south>%0.16g</south>\n",indent,south);
+	fprintf(filout,"%s  <east>%0.16g</east>\n",indent,east);
+	fprintf(filout,"%s  <west>%0.16g</west>\n",indent,west);
+	fprintf(filout,"%s  <rotation>%0.16g</rotation>\n",indent,rotation);
+
+	fprintf(filout,"%s</LatLonBox>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LatLonBox::Read {{{*/
+void  KML_LatLonBox::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</LatLonBox",11)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LatLonBox::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LatLonBox::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<north>"))
+			KMLFileTokenParse(&north     ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<south>"))
+			KMLFileTokenParse(&south     ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<east>"))
+			KMLFileTokenParse(&east      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<west>"))
+			KMLFileTokenParse(&west      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<rotation>"))
+			KMLFileTokenParse(&rotation  ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_LatLonBox.h
===================================================================
--- /issm/trunk/src/c/kml/KML_LatLonBox.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_LatLonBox.h	(revision 15396)
@@ -0,0 +1,40 @@
+/*! \file KML_LatLonBox.h 
+ *  \brief: header file for kml_latlonbox object
+ */
+
+#ifndef _KML_LATLONBOX_H_
+#define _KML_LATLONBOX_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_LatLonBox: public KML_Object {
+
+	public:
+
+		double north;
+		double south;
+		double east;
+		double west;
+		double rotation;
+
+		/*KML_LatLonBox constructors, destructors {{{*/
+		KML_LatLonBox();
+		~KML_LatLonBox();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LATLONBOX_H */
Index: /issm/trunk/src/c/kml/KML_LineString.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_LineString.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_LineString.cpp	(revision 15396)
@@ -0,0 +1,231 @@
+/*!\file KML_LineString.cpp
+ * \brief: implementation of the kml_linestring object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_LineString.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_LineString::KML_LineString(){{{*/
+KML_LineString::KML_LineString(){
+
+	extrude   =false;
+	tessellate=false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	ncoord    =0;
+	coords    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_LineString::~KML_LineString(){{{*/
+KML_LineString::~KML_LineString(){
+
+	if (coords) xDelete<double>(coords);
+
+	coords    =NULL;
+	ncoord    =0;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_LineString::Echo {{{*/
+void  KML_LineString::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_LineString:\n");
+	KML_Geometry::Echo();
+
+	if(flag) _printf0_("       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_("    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_("       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_("        coords: (ncoord=" << ncoord << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::DeepEcho {{{*/
+void  KML_LineString::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_LineString::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::DeepEcho {{{*/
+void  KML_LineString::DeepEcho(const char* indent){
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_LineString:\n");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_(indent << "        coords: (ncoord=" << ncoord << ")\n");
+	for (i=0; i<ncoord; i++)
+		if(flag) _printf0_(indent << "                (" << coords[3*i+0] << "," << coords[3*i+1] << "," << coords[3*i+2] << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::Write {{{*/
+void  KML_LineString::Write(FILE* filout,const char* indent){
+
+	int   i;
+
+	fprintf(filout,"%s<LineString",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+	fprintf(filout,"%s  <extrude>%d</extrude>\n",indent,(extrude ? 1 : 0));
+	fprintf(filout,"%s  <tessellate>%d</tessellate>\n",indent,(tessellate ? 1 : 0));
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+	fprintf(filout,"%s  <coordinates>\n",indent);
+
+/*  loop over the coordinates for the linestring  */
+
+	for (i=0; i<ncoord; i++)
+		fprintf(filout,"%s    %0.16g,%0.16g,%0.16g\n",indent, coords[3*i+0],coords[3*i+1],coords[3*i+2]);
+
+	fprintf(filout,"%s  </coordinates>\n",indent);
+	fprintf(filout,"%s</LineString>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::Read {{{*/
+void  KML_LineString::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</LineString",12)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LineString::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LineString::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_LINESTRING_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&coords    ,&ncoord    ,0,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::WriteExp {{{*/
+void  KML_LineString::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int     i;
+	double  *lat,*lon,*x,*y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude into vectors  */
+
+	lat=xNew<IssmDouble>(ncoord);
+	lon=xNew<IssmDouble>(ncoord);
+	for (i=0; i<ncoord; i++) {
+		lon[i]=coords[3*i+0];
+		lat[i]=coords[3*i+1];
+	}
+
+/*  convert latitude and longitude to x and y  */
+
+	x  =xNew<IssmDouble>(ncoord);
+	y  =xNew<IssmDouble>(ncoord);
+	if (sgn) {
+		Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
+	}
+	else {
+		memcpy(x,lon,ncoord*sizeof(IssmDouble));
+		memcpy(y,lat,ncoord*sizeof(IssmDouble));
+	}
+
+/*  write header  */
+
+	memcpy(nstr2,nstr,(strlen(nstr)+1)*sizeof(char));
+
+	for (i=0; i<strlen(nstr2); i++)
+		if ((nstr2[i] == ' ') || (nstr2[i] == '\t'))
+			nstr2[i]='_';
+	fprintf(fid,"## Name:%s\n",nstr2);
+	fprintf(fid,"## Icon:0\n");
+	fprintf(fid,"# Points Count	Value\n");
+    fprintf(fid,"%u	%s\n",ncoord  ,"1.");
+	fprintf(fid,"# X pos	Y pos\n");
+
+/*  write vertices  */
+
+	for (i=0; i<ncoord; i++)
+	    fprintf(fid,"%lf\t%lf\n",x[i],y[i]);
+
+/*  write blank line  */
+
+	fprintf(fid,"\n");
+
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(x);
+	xDelete<IssmDouble>(lon);
+	xDelete<IssmDouble>(lat);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_LineString.h
===================================================================
--- /issm/trunk/src/c/kml/KML_LineString.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_LineString.h	(revision 15396)
@@ -0,0 +1,43 @@
+/*! \file KML_LineString.h 
+ *  \brief: header file for kml_linestring object
+ */
+
+#ifndef _KML_LINESTRING_H_
+#define _KML_LINESTRING_H_
+
+#define KML_LINESTRING_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Geometry.h"
+/*}}}*/
+
+class KML_LineString: public KML_Geometry {
+
+	public:
+
+		bool    extrude;
+		bool    tessellate;
+		char    altmode[KML_LINESTRING_ALTMODE_LENGTH+1];
+		int     ncoord;
+		double *coords;
+
+		/*KML_LineString constructors, destructors {{{*/
+		KML_LineString();
+		~KML_LineString();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINESTRING_H */
Index: /issm/trunk/src/c/kml/KML_LineStyle.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_LineStyle.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_LineStyle.cpp	(revision 15396)
@@ -0,0 +1,133 @@
+/*!\file KML_LineStyle.cpp
+ * \brief: implementation of the kml_linestyle object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_LineStyle.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_LineStyle::KML_LineStyle(){{{*/
+KML_LineStyle::KML_LineStyle(){
+
+	width     =1.;
+
+}
+/*}}}*/
+/*FUNCTION KML_LineStyle::~KML_LineStyle(){{{*/
+KML_LineStyle::~KML_LineStyle(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_LineStyle::Echo {{{*/
+void  KML_LineStyle::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_LineStyle:\n");
+	KML_ColorStyle::Echo();
+
+	if(flag) _printf0_("         width: " << width << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineStyle::DeepEcho {{{*/
+void  KML_LineStyle::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_LineStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineStyle::DeepEcho {{{*/
+void  KML_LineStyle::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_LineStyle:\n");
+	KML_ColorStyle::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "         width: " << width << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineStyle::Write {{{*/
+void  KML_LineStyle::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<LineStyle",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_ColorStyle::Write(filout,indent);
+
+	fprintf(filout,"%s  <width>%g</width>\n",indent,width);
+
+	fprintf(filout,"%s</LineStyle>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineStyle::Read {{{*/
+void  KML_LineStyle::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</LineStyle",11)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LineStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LineStyle::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<width>"))
+			KMLFileTokenParse(&width     ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_ColorStyle::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_LineStyle.h
===================================================================
--- /issm/trunk/src/c/kml/KML_LineStyle.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_LineStyle.h	(revision 15396)
@@ -0,0 +1,36 @@
+/*! \file KML_LineStyle.h 
+ *  \brief: header file for kml_linestyle object
+ */
+
+#ifndef _KML_LINESTYLE_H_
+#define _KML_LINESTYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_ColorStyle.h"
+/*}}}*/
+
+class KML_LineStyle: public KML_ColorStyle {
+
+	public:
+
+		float width;
+
+		/*KML_LineStyle constructors, destructors {{{*/
+		KML_LineStyle();
+		~KML_LineStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINESTYLE_H */
Index: /issm/trunk/src/c/kml/KML_LinearRing.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_LinearRing.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_LinearRing.cpp	(revision 15396)
@@ -0,0 +1,224 @@
+/*!\file KML_LinearRing.cpp
+ * \brief: implementation of the kml_linearring object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_LinearRing.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_LinearRing::KML_LinearRing(){{{*/
+KML_LinearRing::KML_LinearRing(){
+
+	extrude   =false;
+	tessellate=false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	ncoord    =0;
+	coords    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_LinearRing::~KML_LinearRing(){{{*/
+KML_LinearRing::~KML_LinearRing(){
+
+	if (coords) xDelete<double>(coords);
+
+	coords    =NULL;
+	ncoord    =0;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_LinearRing::Echo {{{*/
+void  KML_LinearRing::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_LinearRing:\n");
+	KML_Geometry::Echo();
+
+	if(flag) _printf0_("       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_("    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_("       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_("        coords: (ncoord=" << ncoord << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LinearRing::DeepEcho {{{*/
+void  KML_LinearRing::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_LinearRing::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LinearRing::DeepEcho {{{*/
+void  KML_LinearRing::DeepEcho(const char* indent){
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_LinearRing:\n");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_(indent << "        coords: (ncoord=" << ncoord << ")\n");
+	for (i=0; i<ncoord; i++)
+		if(flag)_printf_(indent << "                (" <<coords[3*i+0] << "," <<coords[3*i+1] << "," <<coords[3*i+2] << ")\n\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LinearRing::Write {{{*/
+void  KML_LinearRing::Write(FILE* filout,const char* indent){
+
+	int   i;
+
+	fprintf(filout,"%s<LinearRing",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+	fprintf(filout,"%s  <extrude>%d</extrude>\n",indent,(extrude ? 1 : 0));
+	fprintf(filout,"%s  <tessellate>%d</tessellate>\n",indent,(tessellate ? 1 : 0));
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+	fprintf(filout,"%s  <coordinates>\n",indent);
+
+/*  loop over the coordinates for the linearring  */
+
+	for (i=0; i<ncoord; i++)
+		fprintf(filout,"%s    %0.16g,%0.16g,%0.16g\n",indent,coords[3*i+0],coords[3*i+1],coords[3*i+2]);
+
+	fprintf(filout,"%s  </coordinates>\n",indent);
+	fprintf(filout,"%s</LinearRing>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LinearRing::Read {{{*/
+void  KML_LinearRing::Read(FILE* fid,char* kstr){
+
+	char  *kstri = NULL;
+	int    ncom  = 0;
+	char **pcom  = NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,kstr)) return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,&ncom,&pcom)){
+		if (!strncmp(kstri,"</LinearRing",12)){
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LinearRing::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LinearRing::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude,kstri,fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,kstri,fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse(altmode,NULL,KML_LINEARRING_ALTMODE_LENGTH,kstri,fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&coords,&ncoord,3,0,kstri,fid);
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LinearRing::WriteExp {{{*/
+void  KML_LinearRing::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int     i;
+	double  *lat,*lon,*x,*y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude into vectors  */
+
+	lat=xNew<IssmDouble>(ncoord);
+	lon=xNew<IssmDouble>(ncoord);
+	for (i=0; i<ncoord; i++) {
+		lon[i]=coords[3*i+0];
+		lat[i]=coords[3*i+1];
+	}
+
+/*  convert latitude and longitude to x and y  */
+
+	x  =xNew<IssmDouble>(ncoord);
+	y  =xNew<IssmDouble>(ncoord);
+	if (sgn) {
+		Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
+	}
+	else {
+		memcpy(x,lon,ncoord*sizeof(IssmDouble));
+		memcpy(y,lat,ncoord*sizeof(IssmDouble));
+	}
+
+/*  write header  */
+
+	memcpy(nstr2,nstr,(strlen(nstr)+1)*sizeof(char));
+
+	for (i=0; i<strlen(nstr2); i++)
+		if ((nstr2[i] == ' ') || (nstr2[i] == '\t'))
+			nstr2[i]='_';
+	fprintf(fid,"## Name:%s\n",nstr2);
+	fprintf(fid,"## Icon:0\n");
+	fprintf(fid,"# Points Count	Value\n");
+	if ((lat[ncoord-1] != lat[0]) || (lon[ncoord-1] != lon[0]))
+	    fprintf(fid,"%u	%s\n",ncoord+1,"1.");
+	else
+	    fprintf(fid,"%u	%s\n",ncoord  ,"1.");
+	fprintf(fid,"# X pos	Y pos\n");
+
+/*  write vertices, making sure ring is closed  */
+
+	for (i=0; i<ncoord; i++)
+	    fprintf(fid,"%lf\t%lf\n",x[i],y[i]);
+	if ((lat[ncoord-1] != lat[0]) || (lon[ncoord-1] != lon[0]))
+	    fprintf(fid,"%lf\t%lf\n",x[0],y[0]);
+
+/*  write blank line  */
+
+	fprintf(fid,"\n");
+
+	xDelete<double>(y);
+	xDelete<double>(x);
+	xDelete<double>(lon);
+	xDelete<double>(lat);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_LinearRing.h
===================================================================
--- /issm/trunk/src/c/kml/KML_LinearRing.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_LinearRing.h	(revision 15396)
@@ -0,0 +1,43 @@
+/*! \file KML_LinearRing.h 
+ *  \brief: header file for kml_linearring object
+ */
+
+#ifndef _KML_LINEARRING_H_
+#define _KML_LINEARRING_H_
+
+#define KML_LINEARRING_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Geometry.h"
+/*}}}*/
+
+class KML_LinearRing: public KML_Geometry {
+
+	public:
+
+		bool     extrude;
+		bool     tessellate;
+		char     altmode[KML_LINEARRING_ALTMODE_LENGTH+1];
+		int      ncoord;
+		double  *coords;
+
+		/*KML_LinearRing constructors, destructors {{{*/
+		KML_LinearRing();
+		~KML_LinearRing();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINEARRING_H */
Index: /issm/trunk/src/c/kml/KML_MultiGeometry.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_MultiGeometry.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_MultiGeometry.cpp	(revision 15396)
@@ -0,0 +1,204 @@
+/*!\file KML_MultiGeometry.cpp
+ * \brief: implementation of the kml_multigeometry object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Object.h"
+#include "./KML_Point.h"
+#include "./KML_Polygon.h"
+#include "./KML_LineString.h"
+#include "./KML_LinearRing.h"
+#include "./KMLFileReadUtils.h"
+#include "./KML_MultiGeometry.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_MultiGeometry::KML_MultiGeometry(){{{*/
+KML_MultiGeometry::KML_MultiGeometry(){
+
+	geometry  =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_MultiGeometry::~KML_MultiGeometry(){{{*/
+KML_MultiGeometry::~KML_MultiGeometry(){
+
+	if (geometry) {
+		delete geometry;
+		geometry  =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_MultiGeometry::Echo {{{*/
+void  KML_MultiGeometry::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Multigeometry:\n");
+	KML_Geometry::Echo();
+
+	if(flag) _printf0_("      geometry: (size=" << geometry->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_MultiGeometry::DeepEcho {{{*/
+void  KML_MultiGeometry::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_MultiGeometry::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_MultiGeometry::DeepEcho {{{*/
+void  KML_MultiGeometry::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Multigeometry:\n");
+	KML_Geometry::DeepEcho(indent);
+
+/*  loop over the geometry elements for the multigeometry  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (geometry->Size())
+		for (i=0; i<geometry->Size(); i++) {
+			if(flag) _printf0_(indent << "      geometry: -------- begin [" << i << "] --------\n");
+			((KML_Geometry *)geometry->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "      geometry: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "      geometry: [empty]\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_MultiGeometry::Write {{{*/
+void  KML_MultiGeometry::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent2[81];
+
+	fprintf(filout,"%s<MultiGeometry",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+/*  loop over the geometry elements for the multigeometry  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	for (i=0; i<geometry->Size(); i++)
+		((KML_Geometry *)geometry->GetObjectByOffset(i))->Write(filout,indent2);
+
+	fprintf(filout,"%s</MultiGeometry>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_MultiGeometry::Read {{{*/
+void  KML_MultiGeometry::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+	KML_Object*  kobj;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</MultiGeometry",15)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_MultiGeometry::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_MultiGeometry::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<Point", 6)) {
+			kobj=(KML_Object*)new KML_Point();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LineString",11)) {
+			kobj=(KML_Object*)new KML_LineString();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LinearRing",11)) {
+			kobj=(KML_Object*)new KML_LinearRing();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Polygon", 8)) {
+			kobj=(KML_Object*)new KML_Polygon();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<MultiGeometry",14)) {
+			kobj=(KML_Object*)new KML_MultiGeometry();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_MultiGeometry::WriteExp {{{*/
+void  KML_MultiGeometry::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+
+/*  loop over the geometry elements for the multigeometry  */
+
+	for (i=0; i<geometry->Size(); i++)
+		((KML_Object *)geometry->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_MultiGeometry.h
===================================================================
--- /issm/trunk/src/c/kml/KML_MultiGeometry.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_MultiGeometry.h	(revision 15396)
@@ -0,0 +1,39 @@
+/*! \file KML_MultiGeometry.h 
+ *  \brief: header file for kml_multigeometry object
+ */
+
+#ifndef _KML_MULTIGEOMETRY_H_
+#define _KML_MULTIGEOMETRY_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Geometry.h"
+class KML_Geometry;
+class DataSet;
+/*}}}*/
+
+class KML_MultiGeometry: public KML_Geometry {
+
+	public:
+
+		DataSet* geometry;
+
+		/*KML_MultiGeometry constructors, destructors {{{*/
+		KML_MultiGeometry();
+		~KML_MultiGeometry();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_MULTIGEOMETRY_H */
Index: /issm/trunk/src/c/kml/KML_Object.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Object.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Object.cpp	(revision 15396)
@@ -0,0 +1,398 @@
+/*!\file KML_Object.cpp
+ * \brief: implementation of the kml_object abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Object.h"
+#include "./KML_Attribute.h"
+#include "./KML_Comment.h"
+#include "./KML_Unknown.h"
+#include "./KML_LatLonBox.h"
+#include "./KML_Icon.h"
+#include "./KML_MultiGeometry.h"
+#include "./KML_Document.h"
+#include "./KML_LinearRing.h"
+#include "./KML_LineStyle.h"
+#include "./KML_LineString.h"
+#include "./KML_PolyStyle.h"
+#include "./KML_Polygon.h"
+#include "./KML_Point.h"
+#include "./KML_GroundOverlay.h"
+#include "./KML_Placemark.h"
+#include "./KML_Folder.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Object::KML_Object(){{{*/
+KML_Object::KML_Object(){
+
+	attrib    =new DataSet;
+	commnt    =new DataSet;
+	kmlobj    =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_Object::~KML_Object(){{{*/
+KML_Object::~KML_Object(){
+
+	if (attrib) {
+		delete attrib;
+		attrib    =NULL;
+	}
+	if (commnt) {
+		delete commnt;
+		commnt    =NULL;
+	}
+	if (kmlobj) {
+		delete kmlobj;
+		kmlobj    =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Object::Echo {{{*/
+void  KML_Object::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("        attrib: (size=" << attrib->Size() << ")\n");
+	if(flag) _printf0_("        commnt: (size=" << commnt->Size() << ")\n");
+	if(flag) _printf0_("        kmlobj: (size=" << kmlobj->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::DeepEcho {{{*/
+void  KML_Object::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::DeepEcho {{{*/
+void  KML_Object::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+/*  loop over the attributes for the object  */
+
+	if (attrib->Size())
+		for (i=0; i<attrib->Size(); i++) {
+			((KML_Attribute *)attrib->GetObjectByOffset(i))->DeepEcho(indent);
+		}
+	else
+		if(flag) _printf0_(indent << "        attrib: [empty]\n");
+
+/*  loop over the comments for the object  */
+
+	if (commnt->Size())
+		for (i=0; i<commnt->Size(); i++) {
+			((KML_Comment *)commnt->GetObjectByOffset(i))->DeepEcho(indent);
+		}
+	else
+		if(flag) _printf0_(indent << "        commnt: [empty]\n");
+
+/*  loop over the unknown objects for the object  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (kmlobj->Size())
+		for (i=0; i<kmlobj->Size(); i++) {
+            if(flag) _printf0_(indent << "        kmlobj: -------- begin [" << i << "] --------\n");
+			((KML_Unknown *)kmlobj->GetObjectByOffset(i))->DeepEcho(indent2);
+            if(flag) _printf0_(indent << "        kmlobj: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "        kmlobj: [empty]\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::Write {{{*/
+void  KML_Object::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent2[81];
+
+//  attributes always written in keyword line of derived classes
+//  comments always written after keyword line of derived classes
+
+/*  loop over the unknown objects for the object  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (kmlobj->Size())
+		for (i=0; i<kmlobj->Size(); i++) {
+			((KML_Unknown *)kmlobj->GetObjectByOffset(i))->Write(filout,indent2);
+		}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::Read {{{*/
+void  KML_Object::Read(FILE* fid,char* kstr){
+
+	KML_Object*  kobj;
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Object", 8))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Object::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Object::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<Placemark",10)) {
+		kobj=(KML_Object*)new KML_Placemark();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Folder", 7)) {
+		kobj=(KML_Object*)new KML_Folder();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Document", 9)) {
+		kobj=(KML_Object*)new KML_Document();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<GroundOverlay",14)) {
+		kobj=(KML_Object*)new KML_GroundOverlay();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<LatLonBox",10)) {
+		kobj=(KML_Object*)new KML_LatLonBox();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Icon", 5)) {
+		kobj=(KML_Object*)new KML_Icon();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Point", 6)) {
+		kobj=(KML_Object*)new KML_Point();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<LineString",11)) {
+		kobj=(KML_Object*)new KML_LineString();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<LinearRing",11)) {
+		kobj=(KML_Object*)new KML_LinearRing();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Polygon", 8)) {
+		kobj=(KML_Object*)new KML_Polygon();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<MultiGeometry",14)) {
+		kobj=(KML_Object*)new KML_MultiGeometry();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+//	else if (!strncmp(kstr,"<IconStyle",10)) {
+//		kobj=(KML_Object*)new KML_IconStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+//	else if (!strncmp(kstr,"<LabelStyle",11)) {
+//		kobj=(KML_Object*)new KML_LabelStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+	else if (!strncmp(kstr,"<LineStyle",10)) {
+		kobj=(KML_Object*)new KML_LineStyle();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<PolyStyle",10)) {
+		kobj=(KML_Object*)new KML_PolyStyle();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+//	else if (!strncmp(kstr,"<BalloonStyle",13)) {
+//		kobj=(KML_Object*)new KML_BalloonStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+//	else if (!strncmp(kstr,"<ListStyle",10)) {
+//		kobj=(KML_Object*)new KML_ListStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+	else if (!strncmp(kstr,"<",1)) {
+		_printf0_("KML_Object::Read -- Unrecognized opening tag " << kstr << ".\n");
+//		KMLFileTagSkip(kstr,
+//					   fid);
+		kobj=(KML_Object*)new KML_Unknown();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::WriteExp {{{*/
+void  KML_Object::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	;
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::AddAttrib {{{*/
+void  KML_Object::AddAttrib(const char* name,const char* value){
+
+	KML_Attribute* katt=NULL;
+
+	katt=new KML_Attribute();
+	katt->Alloc(name,value);
+	katt->Add(attrib);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::FindAttrib {{{*/
+void  KML_Object::FindAttrib(char** pvalue,char* name,char* deflt){
+
+	int   i;
+	KML_Attribute* katt=NULL;
+
+/*  loop over any attributes for the object  */
+
+	if (attrib->Size())
+		for (i=0; i<attrib->Size(); i++)
+			if (!strcmp(((KML_Attribute *)attrib->GetObjectByOffset(i))->name,name)) {
+				katt=(KML_Attribute *)attrib->GetObjectByOffset(i);
+				break;
+			}
+
+/*  if found, get the value; otherwise use the default  */
+
+	if (katt)
+		katt->Get(pvalue,deflt);
+	else {
+		*pvalue=xNew<char>(strlen(deflt)+1);
+		memcpy(*pvalue,deflt,(strlen(deflt)+1)*sizeof(char));
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::WriteAttrib {{{*/
+void  KML_Object::WriteAttrib(FILE* filout,const char* indent){
+
+//  attributes always written in keyword line of kml_object
+
+/*  loop over any attributes for the object  */
+
+	if (attrib->Size())
+		for (int i=0; i<attrib->Size(); i++)
+			((KML_Attribute *)attrib->GetObjectByOffset(i))->Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::AddCommnt {{{*/
+void  KML_Object::AddCommnt(int ncom,char** pcom){
+
+	int   i;
+	KML_Comment* kcom=NULL;
+
+	for (i=0; i<ncom; i++) {
+		kcom=new KML_Comment();
+		kcom->Alloc(pcom[i]);
+		kcom->Add(commnt);
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::AddCommnt {{{*/
+void  KML_Object::AddCommnt(char* value){
+
+	KML_Comment* kcom=NULL;
+
+	kcom=new KML_Comment();
+	kcom->Alloc(value);
+	kcom->Add(commnt);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::FindCommnt {{{*/
+void  KML_Object::FindCommnt(char** pvalue,int inum){
+
+	KML_Comment* kcom=NULL;
+
+/*  loop over any comments for the object  */
+
+	if (inum <= commnt->Size())
+		kcom=(KML_Comment *)commnt->GetObjectByOffset(inum-1);
+
+/*  if found, get the value; otherwise use the NULL  */
+
+	if (kcom)
+		kcom->Get(pvalue);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::WriteCommnt {{{*/
+void  KML_Object::WriteCommnt(FILE* filout,const char* indent){
+
+	int   i;
+
+//  comments always written after keyword line of kml_object
+
+/*  loop over any comments for the object  */
+
+	if (commnt->Size())
+		for (i=0; i<commnt->Size(); i++)
+			((KML_Comment *)commnt->GetObjectByOffset(i))->Write(filout,indent);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Object.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Object.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Object.h	(revision 15396)
@@ -0,0 +1,47 @@
+/*! \file KML_Object.h 
+ *  \brief: header file for kml_object abstract object
+ */
+
+#ifndef _KML_OBJECT_H_
+#define _KML_OBJECT_H_
+
+/*Headers:{{{*/
+#include "../shared/shared.h"
+#include "../datastructures/datastructures.h"
+/*}}}*/
+
+class KML_Object: public Object {
+
+	public:
+
+		DataSet* attrib;
+		DataSet* commnt;
+		DataSet* kmlobj;
+
+		/*KML_Object constructors, destructors {{{*/
+		KML_Object();
+		~KML_Object();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(const char* indent);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		virtual void  Write(FILE* fid,const char* indent)=0;
+		virtual void  Read(FILE* fid,char* kstr)=0;
+		virtual void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		virtual void  AddAttrib(const char* name,const char* value);
+		virtual void  FindAttrib(char** pvalue,char* name,char* deflt);
+		virtual void  WriteAttrib(FILE* fid,const char* indent);
+		virtual void  AddCommnt(int ncom,char** pcom);
+		virtual void  AddCommnt(char* value);
+		virtual void  FindCommnt(char** pvalue,int inum);
+		virtual void  WriteCommnt(FILE* fid,const char* indent);
+
+};
+#endif  /* _KML_OBJECT_H */
Index: /issm/trunk/src/c/kml/KML_Overlay.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Overlay.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Overlay.cpp	(revision 15396)
@@ -0,0 +1,132 @@
+/*!\file KML_Overlay.cpp
+ * \brief: implementation of the kml_overlay abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KMLFileReadUtils.h"
+#include "./KML_Overlay.h"
+#include "./KML_Icon.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Overlay::KML_Overlay(){{{*/
+KML_Overlay::KML_Overlay(){
+
+	strcpy(color     ,"ffffffff");
+	memcpy(color,"ffffffff",(strlen("ffffffff")+1)*sizeof(char));
+
+	draword   = 0;
+	icon      =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_Overlay::~KML_Overlay(){{{*/
+KML_Overlay::~KML_Overlay(){
+
+	if (icon) {
+		delete icon;
+		icon      =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Overlay::Echo {{{*/
+void  KML_Overlay::Echo(){
+
+	KML_Feature::Echo();
+	_printf0_("         color: \"" << color << "\"\n");
+	_printf0_("       draword: " << draword << "\n");
+	_printf0_("          icon: " << icon << "\n");
+}
+/*}}}*/
+/*FUNCTION KML_Overlay::DeepEcho {{{*/
+void  KML_Overlay::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Overlay::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Overlay::DeepEcho {{{*/
+void  KML_Overlay::DeepEcho(const char* indent){
+
+	char  indent2[81];
+	KML_Feature::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	_printf0_(indent << "         color: " << color << "\n");
+	_printf0_(indent << "       draword: " << draword << "\n");
+	if (icon)
+		icon->DeepEcho(indent2);
+	else
+		_printf0_(indent << "          icon: " << icon << "\n");
+}
+/*}}}*/
+/*FUNCTION KML_Overlay::Write {{{*/
+void  KML_Overlay::Write(FILE* filout,const char* indent){
+
+	char  indent2[81];
+
+	KML_Feature::Write(filout,indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	if (color     && strlen(color))
+		fprintf(filout,"%s  <color>%s</color>\n",indent,color);
+	fprintf(filout,"%s  <drawOrder>%d</drawOrder>\n",indent,draword);
+	if (icon)
+		icon->Write(filout,indent2);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Overlay::Read {{{*/
+void  KML_Overlay::Read(FILE* fid,char* kstr){
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Overlay", 9)) {
+		xDelete<char>(kstr);
+		return;
+	}
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Overlay::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Overlay::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strcmp(kstr,"<color>"))
+		KMLFileTokenParse( color     ,NULL,KML_OVERLAY_COLOR_LENGTH,
+						  kstr,
+						  fid);
+	else if (!strcmp(kstr,"<drawOrder>"))
+		KMLFileTokenParse(&draword   ,
+						  kstr,
+						  fid);
+
+	else if (!strncmp(kstr,"<Icon", 5)) {
+		icon      =new KML_Icon();
+		icon      ->Read(fid,kstr);
+	}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Feature::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Overlay.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Overlay.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Overlay.h	(revision 15396)
@@ -0,0 +1,41 @@
+/*! \file KML_Overlay.h 
+ *  \brief: header file for kml_overlay abstract object
+ */
+
+#ifndef _KML_OVERLAY_H_
+#define _KML_OVERLAY_H_
+
+#define KML_OVERLAY_COLOR_LENGTH  8
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Feature.h"
+class KML_Icon;
+/*}}}*/
+
+class KML_Overlay: public KML_Feature {
+
+	public:
+
+		char  color[KML_OVERLAY_COLOR_LENGTH+1];
+		int   draword;
+		KML_Icon* icon;
+
+		/*KML_Overlay constructors, destructors {{{*/
+		KML_Overlay();
+		~KML_Overlay();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_OVERLAY_H */
Index: /issm/trunk/src/c/kml/KML_Placemark.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Placemark.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Placemark.cpp	(revision 15396)
@@ -0,0 +1,212 @@
+/*!\file KML_Placemark.cpp
+ * \brief: implementation of the kml_placemark object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KMLFileReadUtils.h"
+#include "./KML_Geometry.h"
+#include "./KML_Point.h"
+#include "./KML_LineString.h"
+#include "./KML_Polygon.h"
+#include "./KML_MultiGeometry.h"
+#include "./KML_LinearRing.h"
+#include "./KML_Placemark.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Placemark::KML_Placemark(){{{*/
+KML_Placemark::KML_Placemark(){
+
+	geometry  =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::~KML_Placemark(){{{*/
+KML_Placemark::~KML_Placemark(){
+
+	if (geometry) {
+		delete geometry;
+		geometry  =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Placemark::Echo {{{*/
+void  KML_Placemark::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Placemark:\n");
+	KML_Feature::Echo();
+
+	if(flag) _printf0_("      geometry: (size=" << geometry->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::DeepEcho {{{*/
+void  KML_Placemark::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Placemark::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::DeepEcho {{{*/
+void  KML_Placemark::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Placemark:\n");
+	KML_Feature::DeepEcho(indent);
+
+/*  loop over the geometry elements for the placemark  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (geometry->Size())
+		for (i=0; i<geometry->Size(); i++) {
+			if(flag) _printf0_(indent << "      geometry: -------- begin [" << i << "] --------\n");
+			((KML_Geometry *)geometry->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "      geometry: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "      geometry: [empty]\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::Write {{{*/
+void  KML_Placemark::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent2[81];
+
+	fprintf(filout,"%s<Placemark",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Feature::Write(filout,indent);
+
+/*  loop over the geometry elements for the placemark  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	for (i=0; i<geometry->Size(); i++)
+		((KML_Geometry *)geometry->GetObjectByOffset(i))->Write(filout,indent2);
+
+	fprintf(filout,"%s</Placemark>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::Read {{{*/
+void  KML_Placemark::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+	KML_Object*  kobj;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Placemark",11)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Placemark::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Placemark::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<Point", 6)) {
+			kobj=(KML_Object*)new KML_Point();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LineString",11)) {
+			kobj=(KML_Object*)new KML_LineString();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LinearRing",11)) {
+			kobj=(KML_Object*)new KML_LinearRing();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Polygon", 8)) {
+			kobj=(KML_Object*)new KML_Polygon();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<MultiGeometry",14)) {
+			kobj=(KML_Object*)new KML_MultiGeometry();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Feature::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::WriteExp {{{*/
+void  KML_Placemark::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+	char  nstr2[81];
+
+/*  loop over the geometry elements for the placemark  */
+
+	for (i=0; i<geometry->Size(); i++) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s %s",nstr,name);
+		else
+			sprintf(nstr2,"%s",name);
+
+		((KML_Object *)geometry->GetObjectByOffset(i))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Placemark.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Placemark.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Placemark.h	(revision 15396)
@@ -0,0 +1,39 @@
+/*! \file KML_Placemark.h 
+ *  \brief: header file for kml_placemark object
+ */
+
+#ifndef _KML_PLACEMARK_H_
+#define _KML_PLACEMARK_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Feature.h"
+class KML_Geometry;
+class DataSet;
+/*}}}*/
+
+class KML_Placemark: public KML_Feature {
+
+	public:
+
+		DataSet* geometry;
+
+		/*KML_Placemark constructors, destructors {{{*/
+		KML_Placemark();
+		~KML_Placemark();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_PLACEMARK_H */
Index: /issm/trunk/src/c/kml/KML_Point.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Point.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Point.cpp	(revision 15396)
@@ -0,0 +1,194 @@
+/*!\file KML_Point.cpp
+ * \brief: implementation of the kml_point object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Point.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Point::KML_Point(){{{*/
+KML_Point::KML_Point(){
+
+	extrude   =false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	coords[0] = 0.;
+	coords[1] = 0.;
+	coords[2] = 0.;
+
+}
+/*}}}*/
+/*FUNCTION KML_Point::~KML_Point(){{{*/
+KML_Point::~KML_Point(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Point::Echo {{{*/
+void  KML_Point::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Point:\n");
+	KML_Geometry::Echo();
+
+	if(flag) _printf0_("       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_("       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_("        coords: (" << coords[0] << "," << coords[1] << "," << coords[2] << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::DeepEcho {{{*/
+void  KML_Point::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Point::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::DeepEcho {{{*/
+void  KML_Point::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Point:\n");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_(indent << "        coords: (" << coords[0] << "," << coords[1] << "," << coords[2] << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::Write {{{*/
+void  KML_Point::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<Point",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+	fprintf(filout,"%s  <extrude>%d</extrude>\n",indent,(extrude ? 1 : 0));
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+	fprintf(filout,"%s  <coordinates>%0.16g,%0.16g,%0.16g</coordinates>\n",
+			indent,coords[0],coords[1],coords[2]);
+
+	fprintf(filout,"%s</Point>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::Read {{{*/
+void  KML_Point::Read(FILE* fid,char* kstr){
+
+	double*      pcoords=&coords[0];
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Point", 7)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Point::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Point::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   , kstri, fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_POINT_ALTMODE_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&pcoords   ,NULL,3, kstri, fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::WriteExp {{{*/
+void  KML_Point::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int     i;
+	double  lat,lon,x,y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude  */
+
+	lon=coords[0];
+	lat=coords[1];
+
+/*  convert latitude and longitude to x and y  */
+
+	if (sgn) {
+		Ll2xyx(&x,&y,&lat,&lon,1,sgn,cm,sp);
+	}
+	else {
+		memcpy(&x,&lon,1*sizeof(IssmDouble));
+		memcpy(&y,&lat,1*sizeof(IssmDouble));
+	}
+
+/*  write header  */
+
+	memcpy(nstr2,nstr,(strlen(nstr)+1)*sizeof(char));
+
+	for (i=0; i<strlen(nstr2); i++)
+		if ((nstr2[i] == ' ') || (nstr2[i] == '\t'))
+			nstr2[i]='_';
+	fprintf(fid,"## Name:%s\n",nstr2);
+	fprintf(fid,"## Icon:0\n");
+	fprintf(fid,"# Points Count	Value\n");
+    fprintf(fid,"%u	%s\n",1,"1.");
+	fprintf(fid,"# X pos	Y pos\n");
+
+/*  write vertex  */
+
+    fprintf(fid,"%lf\t%lf\n",x,y);
+
+/*  write blank line  */
+
+	fprintf(fid,"\n");
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Point.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Point.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Point.h	(revision 15396)
@@ -0,0 +1,41 @@
+/*! \file KML_Point.h 
+ *  \brief: header file for kml_point object
+ */
+
+#ifndef _KML_POINT_H_
+#define _KML_POINT_H_
+
+#define KML_POINT_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Geometry.h"
+/*}}}*/
+
+class KML_Point: public KML_Geometry {
+
+	public:
+
+		bool  extrude;
+		char  altmode[KML_POINT_ALTMODE_LENGTH+1];
+		double coords[3];
+
+		/*KML_Point constructors, destructors {{{*/
+		KML_Point();
+		~KML_Point();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POINT_H */
Index: /issm/trunk/src/c/kml/KML_PolyStyle.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_PolyStyle.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_PolyStyle.cpp	(revision 15396)
@@ -0,0 +1,143 @@
+/*!\file KML_PolyStyle.cpp
+ * \brief: implementation of the kml_polystyle object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Object.h"
+#include "./KML_ColorStyle.h"
+#include "./KML_PolyStyle.h"
+#include "./KMLFileReadUtils.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_PolyStyle::KML_PolyStyle(){{{*/
+KML_PolyStyle::KML_PolyStyle(){
+
+	fill      =true;
+	outline   =true;
+
+}
+/*}}}*/
+/*FUNCTION KML_PolyStyle::~KML_PolyStyle(){{{*/
+KML_PolyStyle::~KML_PolyStyle(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_PolyStyle::Echo {{{*/
+void  KML_PolyStyle::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_PolyStyle:\n");
+	KML_ColorStyle::Echo();
+
+	if(flag) _printf0_("          fill: " << fill << "\n");
+	if(flag) _printf0_("       outline: " << outline << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_PolyStyle::DeepEcho {{{*/
+void  KML_PolyStyle::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_PolyStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_PolyStyle::DeepEcho {{{*/
+void  KML_PolyStyle::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_PolyStyle:\n");
+	KML_ColorStyle::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "          fill: " << fill << "\n");
+	if(flag) _printf0_(indent << "       outline: " << outline << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_PolyStyle::Write {{{*/
+void  KML_PolyStyle::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<PolyStyle",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_ColorStyle::Write(filout,indent);
+
+	fprintf(filout,"%s  <fill>%d</fill>\n",indent,fill);
+	fprintf(filout,"%s  <outline>%d</outline>\n",indent,outline);
+
+	fprintf(filout,"%s</PolyStyle>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_PolyStyle::Read {{{*/
+void  KML_PolyStyle::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</PolyStyle",11)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_PolyStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_PolyStyle::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<fill>"))
+			KMLFileTokenParse(&fill      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<outline>"))
+			KMLFileTokenParse(&outline   ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_ColorStyle::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_PolyStyle.h
===================================================================
--- /issm/trunk/src/c/kml/KML_PolyStyle.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_PolyStyle.h	(revision 15396)
@@ -0,0 +1,37 @@
+/*! \file KML_PolyStyle.h 
+ *  \brief: header file for kml_polystyle object
+ */
+
+#ifndef _KML_POLYSTYLE_H_
+#define _KML_POLYSTYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_ColorStyle.h"
+/*}}}*/
+
+class KML_PolyStyle: public KML_ColorStyle {
+
+	public:
+
+		int   fill;
+		int   outline;
+
+		/*KML_PolyStyle constructors, destructors {{{*/
+		KML_PolyStyle();
+		~KML_PolyStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POLYSTYLE_H */
Index: /issm/trunk/src/c/kml/KML_Polygon.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Polygon.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Polygon.cpp	(revision 15396)
@@ -0,0 +1,294 @@
+/*!\file KML_Polygon.cpp
+ * \brief: implementation of the kml_polygon object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_LinearRing.h"
+#include "./KMLFileReadUtils.h"
+#include "./KML_Polygon.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Polygon::KML_Polygon(){{{*/
+KML_Polygon::KML_Polygon(){
+
+	extrude   =false;
+	tessellate=false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	outer     =new DataSet;
+	inner     =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::~KML_Polygon(){{{*/
+KML_Polygon::~KML_Polygon(){
+
+	if (inner) {
+		delete inner;
+		inner     =NULL;
+	}
+
+	if (outer) {
+		delete outer;
+		outer     =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Polygon::Echo {{{*/
+void  KML_Polygon::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Polygon:\n");
+	KML_Geometry::Echo();
+
+	if(flag) _printf0_("       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_("    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_("       altmode: \"" << altmode << "\"\n");
+	if(flag) _printf0_("         outer: (size=" << outer->Size() << ")\n");
+	if(flag) _printf0_("         inner: (size=" << inner->Size() << ")\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::DeepEcho {{{*/
+void  KML_Polygon::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Polygon::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::DeepEcho {{{*/
+void  KML_Polygon::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Polygon:\n");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _printf0_(indent << "       extrude: " << (extrude ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "    tessellate: " << (tessellate ? "true" : "false") << "\n");
+	if(flag) _printf0_(indent << "       altmode: \"" << altmode << "\"\n");
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (outer->Size())
+		for (i=0; i<outer->Size(); i++) {
+			if(flag) _printf0_(indent << "         outer: -------- begin [" << i << "] --------\n");
+			((KML_LinearRing *)outer->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "         outer: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "         outer: [empty]\n");
+
+	if (inner->Size())
+		for (i=0; i<inner->Size(); i++) {
+			if(flag) _printf0_(indent << "         inner: -------- begin [" << i << "] --------\n");
+			((KML_LinearRing *)inner->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _printf0_(indent << "         inner: --------  end  [" << i << "] --------\n");
+		}
+	else
+		if(flag) _printf0_(indent << "         inner: [empty]\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::Write {{{*/
+void  KML_Polygon::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent4[81];
+
+	fprintf(filout,"%s<Polygon",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+	fprintf(filout,"%s  <extrude>%d</extrude>\n",indent,(extrude ? 1 : 0));
+	fprintf(filout,"%s  <tessellate>%d</tessellate>\n",indent,(tessellate ? 1 : 0));
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+
+	memcpy(indent4,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent4,"    ");
+
+/*  check outer boundary for the polygon  */
+
+	fprintf(filout,"%s  <outerBoundaryIs>\n",indent);
+	if (outer->Size())
+		((KML_LinearRing *)outer->GetObjectByOffset(0))->Write(filout,indent4);
+	fprintf(filout,"%s  </outerBoundaryIs>\n",indent);
+
+/*  loop over any inner boundaries for the polygon  */
+
+	for (i=0; i<inner->Size(); i++) {
+		fprintf(filout,"%s  <innerBoundaryIs>\n",indent);
+		((KML_LinearRing *)inner->GetObjectByOffset(i))->Write(filout,indent4);
+		fprintf(filout,"%s  </innerBoundaryIs>\n",indent);
+	}
+
+	fprintf(filout,"%s</Polygon>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::Read {{{*/
+void  KML_Polygon::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	char*        kstrj;
+	int          ncom=0;
+	char**       pcom=NULL;
+	KML_Object*  kobj;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Polygon", 9)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_POLYGON_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+
+		else if (!strcmp(kstri,"<outerBoundaryIs>"))
+
+/*  loop over and process fields within outer boundary  */
+
+			while (kstrj=KMLFileToken(fid,
+									  &ncom,&pcom)) {
+				if      (!strncmp(kstrj,"</outerBoundaryIs",17)) {
+					xDelete<char>(kstrj);
+					break;
+				}
+				else if (!strncmp(kstrj,"</",2))
+				  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
+				else if (strncmp(kstrj,"<",1))
+				  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstrj << "\".\n");}
+
+				else if (!strncmp(kstrj,"<LinearRing",11)) {
+					kobj=(KML_Object*)new KML_LinearRing();
+					kobj->Read(fid,kstrj);
+					outer     ->AddObject((Object*)kobj);
+				}
+
+				else if (!strncmp(kstrj,"<",1))
+					KML_Geometry::Read(fid,kstrj);
+
+				xDelete<char>(kstrj);
+			}
+
+		else if (!strcmp(kstri,"<innerBoundaryIs>"))
+
+/*  loop over and process fields within inner boundaries  */
+
+			while (kstrj=KMLFileToken(fid,
+									  &ncom,&pcom)) {
+				if      (!strncmp(kstrj,"</innerBoundaryIs",17)) {
+					xDelete<char>(kstrj);
+					break;
+				}
+				else if (!strncmp(kstrj,"</",2))
+				  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
+				else if (strncmp(kstrj,"<",1))
+				  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstrj << "\".\n");}
+
+				else if (!strncmp(kstrj,"<LinearRing",11)) {
+					kobj=(KML_Object*)new KML_LinearRing();
+					kobj->Read(fid,kstrj);
+					inner     ->AddObject((Object*)kobj);
+				}
+
+				else if (!strncmp(kstrj,"<",1))
+					KML_Geometry::Read(fid,kstrj);
+
+				xDelete<char>(kstrj);
+			}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::WriteExp {{{*/
+void  KML_Polygon::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+	char  nstr2[81];
+
+/*  check outer boundary for the polygon  */
+
+	if (outer->Size()) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s (outer)",nstr);
+		else
+			sprintf(nstr2,"(outer)");
+
+		((KML_LinearRing *)outer->GetObjectByOffset(0))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+/*  loop over any inner boundaries for the polygon  */
+
+	for (i=0; i<inner->Size(); i++) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s (inner %d of %d)",nstr,i+1,inner->Size());
+		else
+			sprintf(nstr2,"(inner %d of %d)",i+1,inner->Size());
+
+		((KML_LinearRing *)inner->GetObjectByOffset(i))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Polygon.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Polygon.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Polygon.h	(revision 15396)
@@ -0,0 +1,45 @@
+/*! \file KML_Polygon.h 
+ *  \brief: header file for kml_polygon object
+ */
+
+#ifndef _KML_POLYGON_H_
+#define _KML_POLYGON_H_
+
+#define KML_POLYGON_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Geometry.h"
+class KML_LinearRing;
+class DataSet;
+/*}}}*/
+
+class KML_Polygon: public KML_Geometry {
+
+	public:
+
+		bool  extrude;
+		bool  tessellate;
+		char  altmode[KML_POLYGON_ALTMODE_LENGTH+1];
+		DataSet* outer;
+		DataSet* inner;
+
+		/*KML_Polygon constructors, destructors {{{*/
+		KML_Polygon();
+		~KML_Polygon();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POLYGON_H */
Index: /issm/trunk/src/c/kml/KML_Style.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Style.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Style.cpp	(revision 15396)
@@ -0,0 +1,237 @@
+/*!\file KML_Style.cpp
+ * \brief: implementation of the kml_style object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KMLFileReadUtils.h"
+#include "./KML_LineStyle.h"
+#include "./KML_PolyStyle.h"
+#include "./KML_Style.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Style::KML_Style(){{{*/
+KML_Style::KML_Style(){
+
+	icon      =NULL;
+	label     =NULL;
+	line      =NULL;
+	poly      =NULL;
+	balloon   =NULL;
+	list      =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_Style::~KML_Style(){{{*/
+KML_Style::~KML_Style(){
+
+	if (list) {
+//		delete list;
+		list      =NULL;
+	}
+	if (balloon) {
+//		delete balloon;
+		balloon   =NULL;
+	}
+	if (poly) {
+		delete poly;
+		poly      =NULL;
+	}
+	if (line) {
+		delete line;
+		line      =NULL;
+	}
+	if (label) {
+//		delete label;
+		label     =NULL;
+	}
+	if (icon) {
+//		delete icon;
+		icon      =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Style::Echo {{{*/
+void  KML_Style::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Style:\n");
+	KML_StyleSelector::Echo();
+
+	if(flag) _printf0_("          icon: " << icon << "\n");
+	if(flag) _printf0_("         label: " << label << "\n");
+	if(flag) _printf0_("          line: " << line << "\n");
+	if(flag) _printf0_("          poly: " << poly << "\n");
+	if(flag) _printf0_("       balloon: " << balloon << "\n");
+	if(flag) _printf0_("          list: " << list << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Style::DeepEcho {{{*/
+void  KML_Style::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Style::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Style::DeepEcho {{{*/
+void  KML_Style::DeepEcho(const char* indent){
+
+	char  indent2[81];
+	bool  flag=true;
+
+	if(flag) _printf0_(indent << "KML_Style:\n");
+	KML_StyleSelector::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+//	if (icon)
+//		icon->DeepEcho(indent2);
+//	else
+		if(flag) _printf0_(indent << "          icon: " << icon << "\n");
+//	if (label)
+//		label->DeepEcho(indent2);
+//	else
+		if(flag) _printf0_(indent << "         label: " << label << "\n");
+	if (line)
+		line->DeepEcho(indent2);
+	else
+		if(flag) _printf0_(indent << "          line: " << line << "\n");
+	if (poly)
+		poly->DeepEcho(indent2);
+	else
+		if(flag) _printf0_(indent << "          poly: " << poly << "\n");
+//	if (balloon)
+//		balloon->DeepEcho(indent2);
+//	else
+		if(flag) _printf0_(indent << "       balloon: " << balloon << "\n");
+//	if (list)
+//		list->DeepEcho(indent2);
+//	else
+		if(flag) _printf0_(indent << "          list: " << list << "\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Style::Write {{{*/
+void  KML_Style::Write(FILE* filout,const char* indent){
+
+	char  indent2[81];
+
+	fprintf(filout,"%s<Style",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_StyleSelector::Write(filout,indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+//	if (icon)
+//		icon->Write(filout,indent2);
+//	if (label)
+//		label->Write(filout,indent2);
+	if (line)
+		line->Write(filout,indent2);
+	if (poly)
+		poly->Write(filout,indent2);
+//	if (balloon)
+//		balloon->Write(filout,indent2);
+//	if (list)
+//		list->Write(filout,indent2);
+
+	fprintf(filout,"%s</Style>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Style::Read {{{*/
+void  KML_Style::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Style", 7)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Style::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Style::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+//		else if (!strncmp(kstri,"<IconStyle",10)) {
+//			icon      =new KML_IconStyle();
+//			icon      ->Read(fid,kstri);
+//		}
+
+//		else if (!strncmp(kstri,"<LabelStyle",11)) {
+//			label     =new KML_LabelStyle();
+//			label     ->Read(fid,kstri);
+//		}
+
+		else if (!strncmp(kstri,"<LineStyle",10)) {
+			line      =new KML_LineStyle();
+			line      ->Read(fid,kstri);
+		}
+
+		else if (!strncmp(kstri,"<PolyStyle",10)) {
+			poly      =new KML_PolyStyle();
+			poly      ->Read(fid,kstri);
+		}
+
+//		else if (!strncmp(kstri,"<BalloonStyle",13)) {
+//			balloon   =new KML_BalloonStyle();
+//			balloon   ->Read(fid,kstri);
+//		}
+
+//		else if (!strncmp(kstri,"<ListStyle",10)) {
+//			list      =new KML_ListStyle();
+//			list      ->Read(fid,kstri);
+//		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_StyleSelector::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Style.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Style.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Style.h	(revision 15396)
@@ -0,0 +1,43 @@
+/*! \file KML_Style.h 
+ *  \brief: header file for kml_style object
+ */
+
+#ifndef _KML_STYLE_H_
+#define _KML_STYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_StyleSelector.h"
+class KML_LineStyle;
+class KML_PolyStyle;
+/*}}}*/
+
+class KML_Style: public KML_StyleSelector {
+
+	public:
+
+		void* icon;
+		void* label;
+		KML_LineStyle* line;
+		KML_PolyStyle* poly;
+		void* balloon;
+		void* list;
+
+		/*KML_Style constructors, destructors {{{*/
+		KML_Style();
+		~KML_Style();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_STYLE_H */
Index: /issm/trunk/src/c/kml/KML_StyleSelector.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_StyleSelector.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_StyleSelector.cpp	(revision 15396)
@@ -0,0 +1,86 @@
+/*!\file KML_StyleSelector.cpp
+ * \brief: implementation of the kml_styleselector abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_Object.h"
+#include "./KML_StyleSelector.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_StyleSelector::KML_StyleSelector(){{{*/
+KML_StyleSelector::KML_StyleSelector(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_StyleSelector::~KML_StyleSelector(){{{*/
+KML_StyleSelector::~KML_StyleSelector(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_StyleSelector::Echo {{{*/
+void  KML_StyleSelector::Echo(){
+
+	KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_StyleSelector::DeepEcho {{{*/
+void  KML_StyleSelector::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_StyleSelector::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_StyleSelector::DeepEcho {{{*/
+void  KML_StyleSelector::DeepEcho(const char* indent){
+
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_StyleSelector::Write {{{*/
+void  KML_StyleSelector::Write(FILE* filout,const char* indent){
+
+	KML_Object::Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_StyleSelector::Read {{{*/
+void  KML_StyleSelector::Read(FILE* fid,char* kstr){
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</StyleSelector",15))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_StyleSelector::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_StyleSelector::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_StyleSelector.h
===================================================================
--- /issm/trunk/src/c/kml/KML_StyleSelector.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_StyleSelector.h	(revision 15396)
@@ -0,0 +1,34 @@
+/*! \file KML_StyleSelector.h 
+ *  \brief: header file for kml_styleselector abstract object
+ */
+
+#ifndef _KML_STYLESELECTOR_H_
+#define _KML_STYLESELECTOR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_StyleSelector: public KML_Object {
+
+	public:
+
+		/*KML_StyleSelector constructors, destructors {{{*/
+		KML_StyleSelector();
+		~KML_StyleSelector();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_STYLESELECTOR_H */
Index: /issm/trunk/src/c/kml/KML_SubStyle.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_SubStyle.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_SubStyle.cpp	(revision 15396)
@@ -0,0 +1,86 @@
+/*!\file KML_SubStyle.cpp
+ * \brief: implementation of the kml_substyle abstract object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KML_SubStyle.h"
+#include "./KML_Object.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_SubStyle::KML_SubStyle(){{{*/
+KML_SubStyle::KML_SubStyle(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_SubStyle::~KML_SubStyle(){{{*/
+KML_SubStyle::~KML_SubStyle(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_SubStyle::Echo {{{*/
+void  KML_SubStyle::Echo(){
+
+	KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_SubStyle::DeepEcho {{{*/
+void  KML_SubStyle::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_SubStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_SubStyle::DeepEcho {{{*/
+void  KML_SubStyle::DeepEcho(const char* indent){
+
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_SubStyle::Write {{{*/
+void  KML_SubStyle::Write(FILE* filout,const char* indent){
+
+	KML_Object::Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_SubStyle::Read {{{*/
+void  KML_SubStyle::Read(FILE* fid,char* kstr){
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</SubStyle",10))
+		return;
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_SubStyle::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_SubStyle::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_SubStyle.h
===================================================================
--- /issm/trunk/src/c/kml/KML_SubStyle.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_SubStyle.h	(revision 15396)
@@ -0,0 +1,34 @@
+/*! \file KML_SubStyle.h 
+ *  \brief: header file for kml_substyle abstract object
+ */
+
+#ifndef _KML_SUBSTYLE_H_
+#define _KML_SUBSTYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_SubStyle: public KML_Object {
+
+	public:
+
+		/*KML_SubStyle constructors, destructors {{{*/
+		KML_SubStyle();
+		~KML_SubStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_SUBSTYLE_H */
Index: /issm/trunk/src/c/kml/KML_Unknown.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_Unknown.cpp	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Unknown.cpp	(revision 15396)
@@ -0,0 +1,191 @@
+/*!\file KML_Unknown.cpp
+ * \brief: implementation of the kml_unknown object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./KMLFileReadUtils.h"
+#include "./KML_Unknown.h"
+#include "../shared/shared.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Unknown::KML_Unknown(){{{*/
+KML_Unknown::KML_Unknown(){
+
+	name      =NULL;
+	value     =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::~KML_Unknown(){{{*/
+KML_Unknown::~KML_Unknown(){
+
+	if (name      ) xDelete<char>(name);
+	if (value     ) xDelete<char>(value);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Unknown::Echo {{{*/
+void  KML_Unknown::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _printf0_("KML_Unknown " << name << ":\n");
+	KML_Object::Echo();
+
+	if (value     )
+		if(flag) _printf0_("         value: \"" << value << "\"\n");
+    else
+        if(flag) _printf0_("         value: [none]\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::DeepEcho {{{*/
+void  KML_Unknown::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Unknown::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::DeepEcho {{{*/
+void  KML_Unknown::DeepEcho(const char* indent){
+
+	char*        valuei;
+	char*        vtoken;
+	char         nl[]={'\n','\0'};
+	bool         flag=true;
+
+	if(flag) _printf0_(indent << "KML_Unknown " << name << ":\n");
+	KML_Object::DeepEcho(indent);
+
+	if (value     ) {
+		valuei=xNew<char>(strlen(value)+1);
+		memcpy(valuei,value,(strlen(value)+1)*sizeof(char)); 
+
+		vtoken=strtok(valuei,nl);
+		if(flag) _printf0_(indent << "         value: \"" << vtoken);
+
+		while (vtoken=strtok(NULL,nl))
+			if(flag) _printf0_("\n" << indent << "                 " << vtoken);
+		if(flag) _printf0_("\"\n");
+
+		xDelete<char>(valuei);
+	}
+    else
+        if(flag) _printf0_(indent << "         value: [none]\n");
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::Write {{{*/
+void  KML_Unknown::Write(FILE* filout,const char* indent){
+
+	char*        valuei;
+	char*        vtoken;
+	char         nl[]={'\n','\0'};
+
+	fprintf(filout,"%s<%s",indent,name);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	if (value     ) {
+		valuei=xNew<char>(strlen(value)+1);
+		memcpy(valuei,value,(strlen(value)+1)*sizeof(char)); 
+
+		vtoken=strtok(valuei,nl);
+		fprintf(filout,"%s  %s\n",indent,vtoken);
+
+		while (vtoken=strtok(NULL,nl))
+			fprintf(filout,"%s  %s\n",indent,vtoken);
+
+		xDelete<char>(valuei);
+	}
+
+	KML_Object::Write(filout,indent);
+
+	fprintf(filout,"%s</%s>\n",indent,name);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::Read {{{*/
+void  KML_Unknown::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	char*        value2=NULL;
+	int          ncom=0;
+	char**       pcom=NULL;
+	char         nl[]={'\n','\0'};
+
+/*  get object name  */
+
+	name=KMLFileTagName(NULL,
+						kstr);
+//	_printf0_("KML_Unknown::Read -- opening name=" << name << ".\n");
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+//		_printf0_("KML_Unknown::Read -- kstri=" << kstri << ".\n");
+		if      (!strncmp(&kstri[0],"</", 2) &&
+				 !strncmp(&kstri[2],name,strlen(name))) {
+//			_printf0_("KML_Unknown::Read -- closing name=" << name << ".\n");
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Unknown::Read -- Unexpected closing tag " << kstri << ".\n");}
+
+		else if (strncmp(kstri,"<",1)) {
+			if (value) {
+				value2=xNew<char>(strlen(value)+1+strlen(kstri)+1);
+				memcpy(value2,value,(strlen(value)+1)*sizeof(char));
+				xDelete<char>(value);
+				value=value2;
+				value2=NULL;
+//				value=(char *) xrealloc(value,(strlen(value)+1+strlen(kstri)+1)*sizeof(char));
+				strcat(value,nl);
+				strcat(value,kstri);
+			}
+			else {
+				value=xNew<char>(strlen(kstri)+1);
+				memcpy(value,kstri,(strlen(kstri)+1)*sizeof(char));
+			}
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_Unknown.h
===================================================================
--- /issm/trunk/src/c/kml/KML_Unknown.h	(revision 15396)
+++ /issm/trunk/src/c/kml/KML_Unknown.h	(revision 15396)
@@ -0,0 +1,37 @@
+/*! \file KML_Unknown.h 
+ *  \brief: header file for kml_unknown object
+ */
+
+#ifndef _KML_UNKNOWN_H_
+#define _KML_UNKNOWN_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_Unknown: public KML_Object {
+
+	public:
+
+		char* name;
+		char* value;
+
+		/*KML_Unknown constructors, destructors {{{*/
+		KML_Unknown();
+		~KML_Unknown();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_UNKNOWN_H */
Index: /issm/trunk/src/c/kml/kmlobjects.h
===================================================================
--- /issm/trunk/src/c/kml/kmlobjects.h	(revision 15396)
+++ /issm/trunk/src/c/kml/kmlobjects.h	(revision 15396)
@@ -0,0 +1,37 @@
+/* \file kmlobjects.h
+ * \brief: prototype header for all kml related objects.
+ */
+
+#ifndef KML_OBJECTS_H_
+#define KML_OBJECTS_H_
+
+/*KML parsing objects: */
+#include "./KML_Attribute.h"
+#include "./KML_Comment.h"
+#include "./KML_ColorStyle.h"
+#include "./KML_Container.h"
+#include "./KML_Document.h"
+#include "./KML_Feature.h"
+#include "./KML_File.h"
+#include "./KML_Folder.h"
+#include "./KML_Geometry.h"
+#include "./KML_GroundOverlay.h"
+#include "./KML_Icon.h"
+#include "./KML_LatLonBox.h"
+#include "./KML_LinearRing.h"
+#include "./KML_LineString.h"
+#include "./KML_LineStyle.h"
+#include "./KML_MultiGeometry.h"
+#include "./KML_Object.h"
+#include "./KML_Overlay.h"
+#include "./KML_Point.h"
+#include "./KML_Placemark.h"
+#include "./KML_Polygon.h"
+#include "./KML_PolyStyle.h"
+#include "./KML_Style.h"
+#include "./KML_StyleSelector.h"
+#include "./KML_SubStyle.h"
+#include "./KML_Unknown.h"
+#include "./KMLFileReadUtils.h"
+
+#endif
Index: /issm/trunk/src/c/main/globals.h
===================================================================
--- /issm/trunk/src/c/main/globals.h	(revision 15396)
+++ /issm/trunk/src/c/main/globals.h	(revision 15396)
@@ -0,0 +1,18 @@
+/*!\file global.h:
+ * \brief: these are the global variables always needed. 
+ */
+
+#ifndef _GLOBALS_H_
+#define _GLOBALS_H_
+
+#include "../shared/io/Comm/Comm.h"
+#include "../toolkits/ToolkitOptions.h"
+
+/*Communicators: */
+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*/
+char* ToolkitOptions::toolkitoptions;
+
+#endif
Index: /issm/trunk/src/c/main/issm.cpp
===================================================================
--- /issm/trunk/src/c/main/issm.cpp	(revision 15396)
+++ /issm/trunk/src/c/main/issm.cpp	(revision 15396)
@@ -0,0 +1,35 @@
+/*!\file:  issm.cpp
+ * \brief: ISSM main program
+ */ 
+
+#include "./issm.h"
+
+int main(int argc,char **argv){
+
+	/*Initialize exception trapping: */
+	ExceptionTrapBegin();
+
+	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
+	COMM comm_init=EnvironmentInit(argc,argv);
+
+	/*Initialize femmodel from arguments provided command line: */
+	FemModel *femmodel = new FemModel(argc,argv,comm_init);
+
+	/*Solve: */
+	femmodel->Solve();
+
+	/*Output results: */
+	femmodel->OutputResults();
+
+	/*Wrap up: */
+	delete femmodel;
+
+	/*Finalize environment:*/
+	EnvironmentFinalize();
+
+	/*Finalize exception trapping: */
+	ExceptionTrapEnd();
+
+	/*Return unix success: */
+	return 0; 
+}
Index: /issm/trunk/src/c/main/issm.h
===================================================================
--- /issm/trunk/src/c/main/issm.h	(revision 15396)
+++ /issm/trunk/src/c/main/issm.h	(revision 15396)
@@ -0,0 +1,22 @@
+/*!\file: issm.h
+ * \brief prototype wrapper for issm.h
+ */ 
+
+#ifndef _ISSM_H_
+#define _ISSM_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./globals.h" //only include this header file once!
+#include "../shared/shared.h"
+#include "../classes/classes.h"
+#include "../toolkits/toolkits.h"
+#include "../analyses/analyses.h"
+#include "../solutionsequences/solutionsequences.h"
+#include "../modules/modules.h"
+
+#endif //ifndef _ISSM_H_
Index: /issm/trunk/src/c/main/kriging.cpp
===================================================================
--- /issm/trunk/src/c/main/kriging.cpp	(revision 15396)
+++ /issm/trunk/src/c/main/kriging.cpp	(revision 15396)
@@ -0,0 +1,177 @@
+/*!\file:  kriging.cpp
+ * \brief: kriging main parallel program
+ */ 
+
+#include "./issm.h"
+
+/*Local prototypes*/
+void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,char** prootpath,int argc,char **argv);
+void ProcessInputfile(IssmDouble **px,IssmDouble **py,IssmDouble **pdata,int *pnobs,IssmDouble **px_interp,IssmDouble **py_interp,int *pninterp,Options **poptions,FILE* fid);
+
+int main(int argc,char **argv){
+
+	/*I/O: */
+	FILE *output_fid = NULL;
+	FILE *input_fid  = NULL;
+	bool  waitonlock = false;
+
+	/*File names*/
+	char *lockfilename   = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *rootpath       = NULL;
+
+	MPI_Comm comm;
+
+	/*Input*/
+	int         ninterp,nobs;
+	IssmDouble *x        = NULL;
+	IssmDouble *y        = NULL;
+	IssmDouble *data     = NULL;
+	IssmDouble *x_interp = NULL;
+	IssmDouble *y_interp = NULL;
+	Options    *options  = NULL;
+
+	/*Output*/
+	IssmDouble *predictions = NULL;
+	IssmDouble *error       = NULL;
+
+	/*Initialize exception trapping: */
+	ExceptionTrapBegin();
+
+	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
+	comm=EnvironmentInit(argc,argv);
+	IssmComm::SetComm(comm);
+
+	ProcessArguments2(&binfilename,&outbinfilename,&lockfilename,&rootpath,argc,argv);
+
+	/*Process input files*/
+	input_fid=pfopen(binfilename,"rb");
+	ProcessInputfile(&x,&y,&data,&nobs,&x_interp,&y_interp,&ninterp,&options,input_fid);
+	pfclose(input_fid,binfilename);
+
+	_printf0_("call computational core:\n");
+	pKrigingx(&predictions,&error,x,y,data,nobs,x_interp,y_interp,ninterp,options);
+
+	_printf0_("write results to disk:\n");
+	Results *results = new Results();
+	if(IssmComm::GetRank()==0){
+		output_fid=pfopen(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));
+		for(int i=0;i<results->Size();i++){
+			ExternalResult* result=dynamic_cast<ExternalResult*>(results->GetObjectByOffset(i));
+			result->WriteData(output_fid,1);
+		}
+		pfclose(output_fid,outbinfilename);
+	}
+
+	/*Close output and toolkits options file and write lock file if requested*/
+	_printf0_("write lock file:\n");
+	WriteLockFile(lockfilename);
+
+	/*Free ressources */
+	xDelete<char>(lockfilename);
+	xDelete<char>(binfilename);
+	xDelete<char>(outbinfilename);
+	xDelete<char>(rootpath);
+	xDelete<IssmDouble>(x);
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(data);
+	xDelete<IssmDouble>(x_interp);
+	xDelete<IssmDouble>(y_interp);
+	xDelete<IssmDouble>(predictions);
+	xDelete<IssmDouble>(error);
+	delete options;
+	delete results;
+
+	/*Finalize environment:*/
+	EnvironmentFinalize();
+
+	/*Finalize exception trapping: */
+	ExceptionTrapEnd();
+
+	return 0; //unix success return;
+}
+
+void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,char** prootpath,int argc,char **argv){
+	char *modelname      = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *lockfilename   = NULL;
+	char *rootpatharg    = NULL;
+	char *rootpath       = NULL;
+
+	if(argc<1)_error_("Usage error: no execution path provided");
+	if(argc<2)_error_("Usage error: missing model name");
+
+	rootpatharg=argv[1];
+	if(strcmp(strstr(rootpatharg,"/"),"/")!=0){ 
+		rootpath       = xNew<char>(strlen(rootpatharg)+2); sprintf(rootpath,"%s/",rootpatharg);
+	}  
+	else{
+		rootpath       = xNew<char>(strlen(rootpatharg)+1); sprintf(rootpath,"%s",rootpatharg);
+	} 
+
+	modelname=argv[2];
+	if(strstr(modelname,rootpath)==NULL){
+		binfilename    = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s%s",rootpath,modelname,".bin");
+		outbinfilename = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s%s",rootpath,modelname,".outbin");
+		lockfilename   = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s%s",rootpath,modelname,".lock");
+	}
+	else{
+		binfilename    = xNew<char>(strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s",modelname,".bin");
+		outbinfilename = xNew<char>(strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s",modelname,".outbin");
+		lockfilename   = xNew<char>(strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s",modelname,".lock");
+	}
+
+	/*Clean up and assign output pointer*/
+	*pbinfilename=binfilename;
+	*poutbinfilename=outbinfilename;
+	*plockfilename=lockfilename;
+	*prootpath=rootpath;
+}
+
+void ProcessInputfile(IssmDouble **px,IssmDouble **py,IssmDouble **pdata,int *pnobs,IssmDouble **px_interp,IssmDouble **py_interp,int *pninterp,Options **poptions,FILE* fid){
+
+	int      ninterp,nobs,numoptions;
+	IssmDouble  *x        = NULL;
+	IssmDouble  *y        = NULL;
+	IssmDouble  *data     = NULL;
+	IssmDouble  *x_interp = NULL;
+	IssmDouble  *y_interp = NULL;
+	Options *options  = NULL;
+	Option  *option   = NULL;
+
+	int      M,N;
+	IoModel* iomodel = new IoModel();
+	iomodel->fid=fid;
+	iomodel->CheckEnumSync();
+	iomodel->independents=xNew<bool>(MaximumNumberOfEnums); for(int i=0;i<MaximumNumberOfEnums;i++) iomodel->independents[i]=false;
+	iomodel->FetchData(&x,&M,&N,0);        nobs=M*N;
+	iomodel->FetchData(&y,&M,&N,1);        _assert_(M*N==nobs);
+	iomodel->FetchData(&data,&M,&N,2);     _assert_(M*N==nobs);
+	iomodel->FetchData(&x_interp,&M,&N,3); ninterp=M*N;
+	iomodel->FetchData(&y_interp,&M,&N,4); _assert_(M*N==ninterp);
+
+	/*Read options*/
+	options = new Options();
+	iomodel->LastIndex(&N);
+	numoptions=(int)((N-4)/2);
+	for(int i=0;i<numoptions;i++){
+		iomodel->FetchData(&option,5+2*i);
+		options->AddOption(option);
+		option=NULL;
+	}
+
+	/*Assign output pointer*/
+	*px        = x;
+	*py        = y;
+	*pdata     = data;
+	*pnobs     = nobs;
+	*px_interp = x_interp;
+	*py_interp = y_interp;
+	*pninterp  = ninterp;
+	*poptions  = options;
+	delete iomodel;
+}
Index: /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 15396)
@@ -11,10 +11,6 @@
 
 #include "./AverageOntoPartitionx.h"
-#include "../../Container/Container.h"    
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 #include "../../toolkits/toolkits.h"
-#include "../modules.h"
 
 void AverageOntoPartitionx(double** paverage, Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vertex_response){
@@ -63,7 +59,7 @@
 	/*Free ressources:*/
 	xDelete<double>(qmu_part);
-	xdelete(&partition_contributions);
-	xdelete(&partition_areas);
-	xdelete(&vec_average);
+	delete partition_contributions;
+	delete partition_areas;
+	delete vec_average;
 
 	/*Assign output pointers:*/
Index: /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h
===================================================================
--- /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _AVERAGEONTOPARTITIONXX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 void AverageOntoPartitionx(double** average, Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vertex_response);
Index: /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 15396)
@@ -5,7 +5,6 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../classes/bamg/bamgobjects.h"
+#include "../../bamg/bamgobjects.h"
 
 using namespace bamg;
Index: /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h
===================================================================
--- /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h	(revision 15396)
@@ -6,5 +6,6 @@
 #define _BAMGCONVERTMESHX_H
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
+#include "../../bamg/bamgobjects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 15396)
@@ -5,7 +5,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
+#include "../../bamg/bamgobjects.h"
 
 using namespace bamg;
Index: /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.h
===================================================================
--- /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.h	(revision 15395)
+++ /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _BAMGTRIANGULATEX_H
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp	(revision 15396)
@@ -3,7 +3,6 @@
  */
 #include "./Bamgx.h"
-#include "../../classes/bamg/bamgobjects.h"
+#include "../../bamg/bamgobjects.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
 
@@ -41,6 +40,6 @@
 
 		//Step1: generate geometry Gh
-		if (verbosity>0) _printLine_("Construction of a mesh from a given geometry");
-		if (verbosity>1) _printLine_("   Processing geometry...");
+		if (verbosity>0) _printf_("Construction of a mesh from a given geometry\n");
+		if (verbosity>1) _printf_("   Processing geometry...\n");
 		Geometry Gh(bamggeom_in,bamgopts);
 
@@ -50,5 +49,5 @@
 
 		//build metric using geometry
-		if (verbosity>1) _printLine_("   Generating Metric...");
+		if (verbosity>1) _printf_("   Generating Metric...\n");
 		for(i=0;i<Gh.nbv;i++){
 			Metric M=Gh[i];
@@ -60,5 +59,5 @@
 
 		//generate mesh
-		if (verbosity>1) _printLine_("   Generating Mesh...");
+		if (verbosity>1) _printf_("   Generating Mesh...\n");
 		Mesh Th(maxnbv,Gh,bamgopts);
 
@@ -73,7 +72,7 @@
 
 		//Build output
-		if (verbosity>1) _printLine_("   Write Mesh...");
+		if (verbosity>1) _printf_("   Write Mesh...\n");
 		Th.WriteMesh(bamgmesh_out,bamgopts);
-		if (verbosity>1) _printLine_("   Write Geometry...");
+		if (verbosity>1) _printf_("   Write Geometry...\n");
 		Gh.WriteGeometry(bamggeom_out,bamgopts);
 
@@ -87,6 +86,6 @@
 
 		// read background mesh 
-		if (verbosity>0) _printLine_("Anisotropic mesh adaptation");
-		if (verbosity>1) _printLine_("   Processing initial mesh and geometry...");
+		if (verbosity>0) _printf_("Anisotropic mesh adaptation\n");
+		if (verbosity>1) _printf_("   Processing initial mesh and geometry...\n");
 		Mesh BTh(bamggeom_in,bamgmesh_in,bamgopts); 
 
@@ -100,9 +99,9 @@
 		//Generate initial metric
 		if (bamgopts->metric){
-			if (verbosity>1) _printLine_("   Processing Metric...");
+			if (verbosity>1) _printf_("   Processing Metric...\n");
 			BTh.ReadMetric(bamgopts);
 		}
 		else { 
-			if (verbosity>1) _printLine_("   Generating initial Metric...");
+			if (verbosity>1) _printf_("   Generating initial Metric...\n");
 			Metric Mhmax(bamgopts->hmax);
 			for (int iv=0;iv<BTh.nbv;iv++) BTh[iv].m = Mhmax;
@@ -111,5 +110,5 @@
 		//use present fields to generate metric if present
 		if (bamgopts->field){
-			if (verbosity>1) _printLine_("   Merge metric with field provided...");
+			if (verbosity>1) _printf_("   Merge metric with field provided...\n");
 			BTh.AddMetric(bamgopts);
 		}
@@ -117,5 +116,5 @@
 		// change using hVertices if provided
 		if(bamgopts->hVertices && bamgopts->hVerticesSize[0]==BTh.nbv){
-			if (verbosity>1) _printLine_("   Merging Metric with hVertices...");
+			if (verbosity>1) _printf_("   Merging Metric with hVertices...\n");
 			for (i=0;i<BTh.nbv;i++){
 				if (!xIsNan<IssmPDouble>(bamgopts->hVertices[i])){
@@ -127,5 +126,5 @@
 		// change using hminVertices if provided
 		if (bamgopts->hminVertices){
-			if (verbosity>1) _printLine_("   Merging Metric with hminVertices...");
+			if (verbosity>1) _printf_("   Merging Metric with hminVertices...\n");
 			for (i=0;i<BTh.nbv;i++){
 				if (!xIsNan<IssmPDouble>(bamgopts->hminVertices[i])){
@@ -140,5 +139,5 @@
 		// change using hmaxVertices if provided
 		if (bamgopts->hmaxVertices){
-			if (verbosity>1) _printLine_("   Merging Metric with hmaxVertices...");
+			if (verbosity>1) _printf_("   Merging Metric with hmaxVertices...\n");
 			for (i=0;i<BTh.nbv;i++){
 				if (!xIsNan<IssmPDouble>(bamgopts->hmaxVertices[i])){
@@ -164,5 +163,5 @@
 
 		//Build new mesh
-		if (verbosity>1) _printLine_("   Generating Mesh...");
+		if (verbosity>1) _printf_("   Generating Mesh...\n");
 		Thr=&BTh,Thb=0;
 		Mesh & Th( *(0 ?  new Mesh(*Thr,&Thr->Gh,Thb,maxnbv) :  new Mesh(maxnbv,BTh,bamgopts,bamgopts->KeepVertices)));
@@ -185,17 +184,17 @@
 		if(verbosity>0) {
 			if (Th.nbt-Th.nbtout-Th.nbq*2){
-				_printLine_("   new number of triangles = " << (Th.nbt-Th.nbtout-Th.nbq*2));
+				_printf_("   new number of triangles = " << (Th.nbt-Th.nbtout-Th.nbq*2) << "\n");
 			}
 			if (Th.nbq ){
-				_printLine_("   new number of quads = " << Th.nbq);
+				_printf_("   new number of quads = " << Th.nbq << "\n");
 			}
 		}
 
 		//Build output
-		if (verbosity>1) _printLine_("   Write Mesh...");
+		if (verbosity>1) _printf_("   Write Mesh...\n");
 		Th.WriteMesh(bamgmesh_out,bamgopts);
-		if (verbosity>1) _printLine_("   Write Geometry...");
+		if (verbosity>1) _printf_("   Write Geometry...\n");
 		Th.Gh.WriteGeometry(bamggeom_out,bamgopts);
-		if (verbosity>1) _printLine_("   Write Metric...");
+		if (verbosity>1) _printf_("   Write Metric...\n");
 		BTh.WriteMetric(bamgopts);
 
@@ -207,5 +206,5 @@
 
 	/*No error return*/
-	if (verbosity>1) _printLine_("   Exiting Bamg.");
+	if (verbosity>1) _printf_("   Exiting Bamg.\n");
 	return noerr;
 
Index: /issm/trunk/src/c/modules/Bamgx/Bamgx.h
===================================================================
--- /issm/trunk/src/c/modules/Bamgx/Bamgx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Bamgx/Bamgx.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _BAMGX_H
 
-#include "../../classes/bamg/bamgobjects.h"
+#include "../../bamg/bamgobjects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/CMakeLists.txt	(revision 15395)
+++ /issm/trunk/src/c/modules/CMakeLists.txt	(revision 15396)
@@ -29,5 +29,4 @@
 add_subdirectory(InputArtificialNoisex)
 add_subdirectory(InputControlUpdatex)
-add_subdirectory(InputConvergencex)
 add_subdirectory(InputDuplicatex)
 add_subdirectory(InputScalex)
Index: /issm/trunk/src/c/modules/Chacox/Chacox.cpp
===================================================================
--- /issm/trunk/src/c/modules/Chacox/Chacox.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Chacox/Chacox.cpp	(revision 15396)
@@ -22,40 +22,40 @@
 	#ifdef _HAVE_CHACO_ //only works if Chaco library has been compiled in.
 
-	extern int Using_Main;	/* is main routine being called? */
-	extern char *PARAMS_FILENAME;	/* name of file with parameter updates */
-	extern double EIGEN_TOLERANCE;	/* tolerance for eigen calculations */
-	extern int OUTPUT_ASSIGN;	/* whether to write assignment to file */
-	extern int DEBUG_MEMORY;	/* debug memory allocation and freeing? */
-	extern int DEBUG_TRACE;	/* trace main execution path */
-	extern int DEBUG_PARAMS;	/* debug flag for reading parameters */
-	extern long RANDOM_SEED;	/* seed for random number generators */
-	extern int ECHO;		/* controls amount of output */
-	extern int PROMPT;		/* prompt for input or not? */
-	extern int PRINT_HEADERS;	/* print lines for output sections? */
-	extern int MATCH_TYPE;      /* matching routine to call */
-	extern double input_time;	/* times data file input */
-	extern double start_time;	/* time partitioning starts */
-	FILE     *params_file;	/* file with parameter value updates */
-	int       global_method;	/* global partitioning method */
-	int       local_method;	/* local partitioning method */
-	double    eigtol;		/* tolerance in eigenvector calculation */
-	int       ndims;		/* dimension of recursive partitioning */
-	int       architecture;	/* 0 => hypercube, d => d-dimensional mesh */
-	int       ndims_tot;	/* total number of cube dimensions to divide */
-	int       mesh_dims[3];	/* dimensions of mesh of processors */
-	long      seed;		/* for random graph mutations */
-	int       rqi_flag;		/* use RQI/Symmlq eigensolver? */
-	int       vmax;		/* if so, how many vertices to coarsen down to? */
-	char      outassignname[NAME_LENGTH];	/* assignment output file name */
-	char      outfilename[NAME_LENGTH];	/* name of output file */
-	char     *outassignptr;	/* name or null pointer for output assignment */
-	char     *outfileptr;	/* name or null pointer for output file */
-	int       nprocs;		/* number of processors being divided into */
-	double    time;		/* timing marker */
-	int       flag;		/* return code from input routines */
-	double   *smalloc();	/* safe version of malloc */
-	//double    seconds();	/* returns elapsed time in seconds */
-	/*int       sfree(), interface(), affirm();
-	void      input_queries(), smalloc_stats(), read_params(), clear_timing();*/
+	extern int     Using_Main;                   /* is main routine being called?                */
+	extern char   *PARAMS_FILENAME;              /* name of file with parameter updates          */
+	extern double  EIGEN_TOLERANCE;              /* tolerance for eigen calculations             */
+	extern int     OUTPUT_ASSIGN;                /* whether to write assignment to file          */
+	extern int     DEBUG_MEMORY;                 /* debug memory allocation and freeing?         */
+	extern int     DEBUG_TRACE;                  /* trace main execution path                    */
+	extern int     DEBUG_PARAMS;                 /* debug flag for reading parameters            */
+	extern long    RANDOM_SEED;                  /* seed for random number generators            */
+	extern int     ECHO;                         /* controls amount of output                    */
+	extern int     PROMPT;                       /* prompt for input or not?                     */
+	extern int     PRINT_HEADERS;                /* print lines for output sections?             */
+	extern int     MATCH_TYPE;                   /* matching routine to call                     */
+	extern double  input_time;                   /* times data file input                        */
+	extern double  start_time;                   /* time partitioning starts                     */
+	FILE          *params_file;                  /* file with parameter value updates            */
+	int            global_method;                /* global partitioning method                   */
+	int            local_method;                 /* local partitioning method                    */
+	double         eigtol;                       /* tolerance in eigenvector calculation         */
+	int            ndims;                        /* dimension of recursive partitioning          */
+	int            architecture;                 /* 0 => hypercube, d => d-dimensional mesh      */
+	int            ndims_tot;                    /* total number of cube dimensions to divide    */
+	int            mesh_dims[3];                 /* dimensions of mesh of processors             */
+	long           seed;                         /* for random graph mutations                   */
+	int            rqi_flag;                     /* use RQI/Symmlq eigensolver?                  */
+	int            vmax;                         /* if so, how many vertices to coarsen down to? */
+	char           outassignname[NAME_LENGTH];   /* assignment output file name                  */
+	char           outfilename[NAME_LENGTH];     /* name of output file                          */
+	char          *outassignptr;                 /* name or null pointer for output assignment   */
+	char          *outfileptr;                   /* name or null pointer for output file         */
+	int            nprocs;                       /* number of processors being divided into      */
+	double         time;                         /* timing marker                                */
+	int            flag;                         /* return code from input routines              */
+	double        *smalloc();                    /* safe version of malloc                       */
+	//double       seconds();                    /* returns elapsed time in seconds              */
+	/*int sfree(), interface(), affirm();
+	void input_queries()  , smalloc_stats(), read_params(), clear_timing();  */
 
 	int i,tvwgt;
@@ -63,10 +63,10 @@
 
 	if (DEBUG_TRACE > 0) {
-		_printLine_("<Entering main>");
+		_printf_("<Entering main>\n");
 	}
 
 	if (PRINT_HEADERS) {
-		_printLine_("\n                    Chaco 2.0");
-		_printLine_("          Sandia National Laboratories\n");
+		_printf_("\n                    Chaco 2.0\n");
+		_printf_("          Sandia National Laboratories\n\n");
 	}
 
@@ -74,6 +74,5 @@
 	params_file = fopen(PARAMS_FILENAME, "r");
 	if (params_file == NULL && DEBUG_PARAMS > 1) {
-		printf("Parameter file `%s' not found; using default parameters.\n",
-			   PARAMS_FILENAME);
+		printf("Parameter file `%s' not found; using default parameters.\n",PARAMS_FILENAME);
 	}
 
@@ -100,6 +99,5 @@
 
 	if ((int)options[OPT_VWGTS] && vwgts) {
-		printf("%s -- Applying weights for %d vertices.\n",
-			   __FUNCT__,nvtxs);
+		printf("%s -- Applying weights for %d vertices.\n",__FUNCT__,nvtxs);
 		tvwgt = 0;
 		for (i=0; i<nvtxs; i++)
@@ -109,9 +107,7 @@
 		tvwgt = nvtxs;
 		if      ( (int)options[OPT_VWGTS] && !vwgts)
-			printf("%s -- Vertex weight flag=%d, but no vertex weights specified.\n",
-				   __FUNCT__,options[OPT_VWGTS]);
+			printf("%s -- Vertex weight flag=%d, but no vertex weights specified.\n",__FUNCT__,(int)options[OPT_VWGTS]);
 		else if (!(int)options[OPT_VWGTS] &&  vwgts)
-			printf("%s -- Vertex weight flag=%d, so specified vertex weights ignored.\n",
-				   __FUNCT__,options[OPT_VWGTS]);
+			printf("%s -- Vertex weight flag=%d, so specified vertex weights ignored.\n",__FUNCT__,(int)options[OPT_VWGTS]);
 	}
 
@@ -122,9 +118,7 @@
 	else {
 		if      ( (int)options[OPT_EWGTS] && !ewgts)
-			printf("%s -- Edge weight flag=%d, but no edge weights specified.\n",
-				   __FUNCT__,options[OPT_EWGTS]);
+			printf("%s -- Edge weight flag=%d, but no edge weights specified.\n",__FUNCT__,(int)options[OPT_EWGTS]);
 		else if (!(int)options[OPT_EWGTS] &&  ewgts)
-			printf("%s -- Edge weight flag=%d, so specified edge weights ignored.\n",
-				   __FUNCT__,options[OPT_EWGTS]);
+			printf("%s -- Edge weight flag=%d, so specified edge weights ignored.\n",__FUNCT__,(int)options[OPT_EWGTS]);
 	}
 
@@ -155,6 +149,5 @@
 	for (i=0; i<start[nvtxs]; adjacency[i++]++);
 
-	printf("\n%s -- Calling Chaco interface:\n\n",
-		   __FUNCT__);
+	printf("\n%s -- Calling Chaco interface:\n\n",__FUNCT__);
 	flag = interface(nvtxs, start, adjacency,
 		  ((int)options[OPT_VWGTS] && vwgts ? vwgts : NULL),
@@ -166,6 +159,5 @@
 		  global_method, local_method, rqi_flag, vmax, ndims,
 		  eigtol, seed);
-	printf("\n%s -- Chaco interface returning flag=%d.\n",
-		   __FUNCT__,flag);
+	printf("\n%s -- Chaco interface returning flag=%d.\n",__FUNCT__,flag);
 
 /*  Reset adjacency matrix in case calling function needs it.  */
@@ -174,5 +166,5 @@
 
 	if (DEBUG_MEMORY > 0) {
-		_printLine_("");
+		_printf_("\n");
 		smalloc_stats();
 	}
@@ -182,5 +174,5 @@
 
 	if (DEBUG_TRACE > 1) {
-		_printLine_("<Leaving main>");
+		_printf_("<Leaving main>\n");
 	}
 
Index: /issm/trunk/src/c/modules/Chacox/Chacox.h
===================================================================
--- /issm/trunk/src/c/modules/Chacox/Chacox.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Chacox/Chacox.h	(revision 15396)
@@ -32,6 +32,5 @@
 #endif
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Chacox/input_parse.cpp
===================================================================
--- /issm/trunk/src/c/modules/Chacox/input_parse.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Chacox/input_parse.cpp	(revision 15396)
@@ -37,18 +37,17 @@
 
 	if (DEBUG_TRACE > 0) {
-		_printLine_("<Entering input_parse>");
+		_printf_("<Entering input_parse>\n");
 	}
 
 	if (PROMPT) {
-		_printLine_("Parallel machine architecture:");
-		_printLine_("  (0) Hypercube");
-		_printLine_("  (1) One-dimensional mesh");
-		_printLine_("  (2) Two-dimensional mesh");
-		_printLine_("  (3) Three-dimensional mesh");
+		_printf_("Parallel machine architecture:\n");
+		_printf_("  (0) Hypercube\n");
+		_printf_("  (1) One-dimensional mesh\n");
+		_printf_("  (2) Two-dimensional mesh\n");
+		_printf_("  (3) Three-dimensional mesh\n");
 	}
 	*architecture = (int)options[OPT_ARCH];
 	if (*architecture < 0 || *architecture > 3) {
-		printf("%s -- Architecture %d must be between 0 and 3.\n",
-			   __FUNCT__,options[OPT_ARCH]);
+		printf("%s -- Architecture %d must be between 0 and 3.\n",__FUNCT__,*architecture);
 		return(-1);
 	}
@@ -56,10 +55,10 @@
 	/* Name output assignment file. */
 	if (PROMPT)
-		_printString_("Assignment output file: ");
+		_printf_("Assignment output file: ");
 	outassignname = NULL;
 
 	/* Name output results file. */
 	if (PROMPT)
-		_printString_("File name for saving run results: ");
+		_printf_("File name for saving run results: ");
 	outfilename = NULL;
 
@@ -74,17 +73,16 @@
 	else {
 		if (PROMPT) {
-			_printLine_("Global partitioning method:");
-			_printLine_("  (1) Multilevel-KL");
-			_printLine_("  (2) Spectral");
-			_printLine_("  (3) Inertial");
-			_printLine_("  (4) Linear");
-			_printLine_("  (5) Random");
-			_printLine_("  (6) Scattered");
-			_printLine_("  (7) Read-from-file");
+			_printf_("Global partitioning method:\n");
+			_printf_("  (1) Multilevel-KL\n");
+			_printf_("  (2) Spectral\n");
+			_printf_("  (3) Inertial\n");
+			_printf_("  (4) Linear\n");
+			_printf_("  (5) Random\n");
+			_printf_("  (6) Scattered\n");
+			_printf_("  (7) Read-from-file\n");
 		}
 		*global_method = (int)options[OPT_GLOBAL];
 		if (*global_method < 1 || *global_method > 7) {
-			printf("%s -- Global method %d must be between 1 and 7.\n",
-				   __FUNCT__,options[OPT_GLOBAL]);
+			printf("%s -- Global method %d must be between 1 and 7.\n",__FUNCT__,*global_method);
 			return(-1);
 		}
@@ -93,22 +91,21 @@
 	if (*global_method == 7) {	/* Name and open input assignment file. */
 		if (PROMPT)
-			_printString_("Assignment input file: ");
+			_printf_("Assignment input file: ");
 	}
 
 	else if (*global_method == 3) {
 		if (PROMPT)
-			_printString_("Geometry input file name: ");
+			_printf_("Geometry input file name: ");
 	}
 
 	else if (*global_method == 2) {
 		if (PROMPT) {
-			_printLine_("Eigensolver:");
-			_printLine_("  (1) Multilevel RQI/Symmlq");
-			_printLine_("  (2) Lanczos"); 
+			_printf_("Eigensolver:\n");
+			_printf_("  (1) Multilevel RQI/Symmlq\n");
+			_printf_("  (2) Lanczos\n"); 
 		}
 		eigensolver = (int)options[OPT_RQI];
 		if (eigensolver < 0 || eigensolver > 2) {
-			printf("%s -- RQI/Symmlq flag %d must be between 0 and 2.\n",
-				   __FUNCT__,options[OPT_RQI]);
+			printf("%s -- RQI/Symmlq flag %d must be between 0 and 2.\n",__FUNCT__,eigensolver);
 			return(-1);
 		}
@@ -116,13 +113,12 @@
 			if (MATCH_TYPE == 5) {	/* geometric matching */
 				if (PROMPT)
-					_printString_("Geometry input file name: ");
+					_printf_("Geometry input file name: ");
 			}
 			*rqi_flag = 1;
 			if (PROMPT)
-				_printString_("Number of vertices to coarsen down to: ");
+				_printf_("Number of vertices to coarsen down to: ");
 			*vmax = (int)options[OPT_VMAX];
 			if (*vmax <= 0) {
-				printf("%s -- Vmax %d must be greater then 0.\n",
-					   __FUNCT__,options[OPT_VMAX]);
+				printf("%s -- Vmax %d must be greater then 0.\n",__FUNCT__,*vmax);
 				return(-1);
 			}
@@ -136,12 +132,11 @@
 		if (MATCH_TYPE == 5) {		/* geometric matching */
 			if (PROMPT)
-				_printString_("Geometry input file name: ");
-		}
-		if (PROMPT)
-			_printString_("Number of vertices to coarsen down to: ");
+				_printf_("Geometry input file name: ");
+		}
+		if (PROMPT)
+			_printf_("Number of vertices to coarsen down to: ");
 		*vmax = (int)options[OPT_VMAX];
 		if (*vmax <= 0) {
-			printf("%s -- Vmax %d must be greater then 0.\n",
-				   __FUNCT__,options[OPT_VMAX]);
+			printf("%s -- Vmax %d must be greater then 0.\n",__FUNCT__,*vmax);
 			return(-1);
 		}
@@ -167,12 +162,11 @@
 	else {
 		if (PROMPT) {
-			_printLine_("Local refinement method:");
-			_printLine_("  (1) Kernighan-Lin");
-			_printLine_("  (2) None");
+			_printf_("Local refinement method:\n");
+			_printf_("  (1) Kernighan-Lin\n");
+			_printf_("  (2) None\n");
 		}
 		*local_method = (int)options[OPT_LOCAL];
 		if (*local_method < 1 || *local_method > 2) {
-			printf("%s -- Local method %d must be 1 and 2.\n",
-				   __FUNCT__,options[OPT_LOCAL]);
+			printf("%s -- Local method %d must be 1 and 2.\n",__FUNCT__,*local_method);
 			return(-1);
 		}
@@ -184,8 +178,8 @@
 		*ndims_tot = 0;
 		if (PROMPT)
-			_printString_("Total number of target hypercube dimensions: ");
+			_printf_("Total number of target hypercube dimensions: ");
 		*ndims_tot = nparts[0];
 		if (*ndims_tot < 1) {
-			_printLine_(" Number of divisions must be at least 1");
+			_printf_(" Number of divisions must be at least 1\n");
 			printf("%s -- Number of divisions %d must be at least 1.\n",
 				   __FUNCT__,nparts[0]);
@@ -199,5 +193,5 @@
 		if (*architecture == 2) {
 			if (PROMPT)
-				_printString_("X and Y extent of of 2-D mesh: ");
+				_printf_("X and Y extent of of 2-D mesh: ");
 			mesh_dims[0] = nparts[0];
 			mesh_dims[1] = nparts[1];
@@ -205,5 +199,5 @@
 		else if (*architecture == 3) {
 			if (PROMPT)
-				_printString_("X, Y and Z extent of 3-D mesh: ");
+				_printf_("X, Y and Z extent of 3-D mesh: ");
 			mesh_dims[0] = nparts[0];
 			mesh_dims[1] = nparts[1];
@@ -212,5 +206,5 @@
 		else {			/* Anything else => 1-D mesh */
 			if (PROMPT)
-				_printString_("Size of 1-D mesh: ");
+				_printf_("Size of 1-D mesh: ");
 			mesh_dims[0] = nparts[0];
 			*architecture = 1;
@@ -226,12 +220,11 @@
 	else if (*nprocs <= 7) {
 		if (PROMPT) {
-			_printLine_("Partitioning dimension: ");
-			_printLine_("  (1) Bisection");
-			_printLine_("  (2) Quadrisection");
+			_printf_("Partitioning dimension: \n");
+			_printf_("  (1) Bisection\n");
+			_printf_("  (2) Quadrisection\n");
 		}
 		*ndims = (int)options[OPT_NDIMS];
 		if (*ndims < 1 || *ndims > 2) {
-			printf("%s -- Ndims %d must be 1 or 2 for %d processors.\n",
-				   __FUNCT__,options[OPT_NDIMS],*nprocs);
+			printf("%s -- Ndims %d must be 1 or 2 for %d processors.\n",__FUNCT__,*ndims,*nprocs);
 			return(-1);
 		}
@@ -239,13 +232,12 @@
 	else {
 		if (PROMPT) {
-			_printLine_("Partitioning dimension: ");
-			_printLine_("  (1) Bisection");
-			_printLine_("  (2) Quadrisection");
-			_printLine_("  (3) Octasection");
+			_printf_("Partitioning dimension: \n");
+			_printf_("  (1) Bisection\n");
+			_printf_("  (2) Quadrisection\n");
+			_printf_("  (3) Octasection\n");
 		}
 		*ndims = (int)options[OPT_NDIMS];
 		if (*ndims < 1 || *ndims > 3) {
-			printf("%s -- Ndims %d must be between 1 and 3 for %d processors.\n",
-				   __FUNCT__,options[OPT_NDIMS],*nprocs);
+			printf("%s -- Ndims %d must be between 1 and 3 for %d processors.\n",__FUNCT__,*ndims,*nprocs);
 			return(-1);
 		}
Index: /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 15396)
@@ -6,7 +6,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void	ComputeBasalStressx( Vector<IssmDouble>** psigma,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,Parameters* parameters){
Index: /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h
===================================================================
--- /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _COMPUTEBASALSTRESSX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp	(revision 15396)
@@ -6,7 +6,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void	ComputeStrainRatex( Vector<IssmDouble>** peps,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,Parameters* parameters){
Index: /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h
===================================================================
--- /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _COMPUTESTRAINRATEX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 15396)
@@ -6,29 +6,27 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../classes/classes.h"
 
 int	ConfigureObjectsx( Elements* elements, Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
+	int i;
 	int noerr=1;
-	int i;
-	Element* element=NULL;
-	Load* load=NULL;
-	Node* node=NULL;
-	Material* material=NULL;
 	int configuration_type;
+	Element  *element  = NULL;
+	Load     *load     = NULL;
+	Node     *node     = NULL;
+	Material *material = NULL;
 
 	/*Get analysis type: */
 	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 
-	if(VerboseMProcessor()) _pprintLine_("      Configuring elements...");
+	if(VerboseMProcessor()) _printf0_("      Configuring elements...\n");
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->Configure(elements,loads,nodes,materials,parameters);
+		element->Configure(elements,loads,nodes,vertices,materials,parameters);
 	}
-	if(VerboseMProcessor()) _pprintLine_("      Configuring loads...");
+	if(VerboseMProcessor()) _printf0_("      Configuring loads...\n");
 	for (i=0;i<loads->Size();i++){
 		load=(Load*)loads->GetObjectByOffset(i);
@@ -37,5 +35,5 @@
 		}
 	}
-	if(VerboseMProcessor()) _pprintLine_("      Configuring nodes...");
+	if(VerboseMProcessor()) _printf0_("      Configuring nodes...\n");
 	for (i=0;i<nodes->Size();i++){
 		node=(Node*)nodes->GetObjectByOffset(i);
@@ -45,5 +43,5 @@
 	}
 
-	if(VerboseMProcessor()) _pprintLine_("      Configuring materials...");
+	if(VerboseMProcessor()) _printf0_("      Configuring materials...\n");
 	for (i=0;i<materials->Size();i++){
 		material=(Material*)materials->GetObjectByOffset(i);
Index: /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.h
===================================================================
--- /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _CONFIGUREOBJECTSX_H
 
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _CONSTRAINTSSTATELOCAL_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /*melting: */
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 15396)
@@ -6,8 +6,5 @@
 #include "./ConstraintsStateLocal.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters){
@@ -20,5 +17,5 @@
 
 	/*Display message*/
-	if(VerboseModule()) _pprintLine_("   Constraining penalties");
+	if(VerboseModule()) _printf0_("   Constraining penalties\n");
 
 	/*recover parameters: */
@@ -28,17 +25,19 @@
 	/*Do we have penalties linked to rifts? In this case, run our special rifts penalty 
 	 * management routine, otherwise, skip : */
+
+	/*No constraints management by default!:*/
+	num_unstable_constraints=0;
+	converged=1;
+
+	#ifdef _HAVE_RIFTS_
 	if (RiftIsPresent(loads,analysis_type)){
 		RiftConstraintsState(&converged,&num_unstable_constraints,loads,min_mechanical_constraints,analysis_type);
 	}
+	#endif
 	#ifdef _HAVE_THERMAL_
-	else if(ThermalIsPresent(loads,analysis_type)){
+	if(ThermalIsPresent(loads,analysis_type)){
 		ThermalConstraintsState(loads,&converged,&num_unstable_constraints,analysis_type);
 	}
 	#endif
-	else{
-		/*Do nothing, no constraints management!:*/
-		num_unstable_constraints=0;
-		converged=1;
-	}
 
 	/*Assign output pointers: */
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _CONSTRAINTSSTATEX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 15396)
@@ -4,7 +4,4 @@
 
 #include "./ConstraintsStateLocal.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../shared/shared.h"
 
@@ -54,5 +51,5 @@
 	}
 	else if(num_unstable_constraints<=min_mechanical_constraints){
-		if(VerboseModule()) _pprintLine_("   freezing constraints");
+		if(VerboseModule()) _printf0_("   freezing constraints\n");
 		RiftFreezeConstraints(loads,configuration_type);
 	}
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 15396)
@@ -10,8 +10,7 @@
 #include "./ContourToMeshx.h"
 
-int ContourToMeshx(SeqVec<double>** pin_nod,SeqVec<double>** pin_elem, double* index, double* x, double* y,DataSet* contours,char* interptype,int nel,int nods, int edgevalue) {
+int ContourToMeshx(double** pin_nod,double** pin_elem, double* index, double* x, double* y,Contours* contours,char* interptype,int nel,int nods, int edgevalue) {
 
 	/*Contour:*/
-	double*  in_nod_serial;
 	double   value;
 
@@ -24,8 +23,8 @@
 
 	/*output: */
-	SeqVec<double>* in_nod=NULL;
-	SeqVec<double>* in_elem=NULL;
-	in_nod  = new SeqVec<double>(nods);
-	in_elem = new SeqVec<double>(nel);
+	double*  in_nod;
+	double*  in_elem;
+	in_nod   = xNewZeroInit<double>(nods);
+	in_elem  = xNewZeroInit<double>(nel);
 
 	/*initialize thread parameters: */
@@ -40,21 +39,12 @@
 	LaunchThread(ContourToMeshxt,(void*)&gate,num);
 
-	/*Assemble in_nod: */
-	in_nod->Assemble();
-
-	/*Get in_nod serialised for next operation: */
-	in_nod_serial=in_nod->ToMPISerial();
-
 	/*Take care of the case where an element interpolation has been requested: */
 	if ((strcmp(interptype,"element")==0) || (strcmp(interptype,"element and node")==0)){
 		for(int n=0;n<nel;n++){
-			if ( (in_nod_serial[ (int)*(index+3*n+0) -1] == 1) && (in_nod_serial[ (int)*(index+3*n+1) -1] == 1) && (in_nod_serial[ (int)*(index+3*n+2) -1] == 1) ){
-				value=1; in_elem->SetValue(n,value,INS_VAL);
+			if ( (in_nod[ (int)*(index+3*n+0) -1] == 1) && (in_nod[ (int)*(index+3*n+1) -1] == 1) && (in_nod[ (int)*(index+3*n+2) -1] == 1) ){
+				value=1; in_elem[n]=value;
 			}
 		}
 	}
-
-	/*Assemble vectors: */
-	in_elem->Assemble();
 
 	/*Assign output pointers: */
@@ -62,7 +52,4 @@
 	*pin_elem=in_elem;
 
-	/*Free ressources:*/
-	xDelete<double>(in_nod_serial);
-
 	return 1;
 }
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.h
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 15396)
@@ -7,20 +7,20 @@
 
 #include "../../shared/shared.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /*threading: */
 typedef struct{
 
-	DataSet *contours;
-	int    nods;
-	int    edgevalue;
-	SeqVec<double> *in_nod;
-	double *x;
-	double *y;
+	Contours *contours;
+	int       nods;
+	int       edgevalue;
+	double   *in_nod;
+	double   *x;
+	double   *y;
 
 } ContourToMeshxThreadStruct;
 
 /* local prototypes: */
-int ContourToMeshx(SeqVec<double>** pin_nods,SeqVec<double>** pin_elem, double* index, double* x, double* y,DataSet* contours,char* interptype,int nel,int nods, int edgevalue);
+int ContourToMeshx(double** pin_nods,double** pin_elem, double* index, double* x, double* y,Contours* contours,char* interptype,int nel,int nods, int edgevalue);
 
 void* ContourToMeshxt(void* vContourToMeshxThreadStruct);
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 15396)
@@ -26,5 +26,5 @@
 
 	/*Contour:*/
-	DataSet* contours=NULL;
+	Contours* contours=NULL;
 
 	/*parameters: */
@@ -33,5 +33,5 @@
 	double* x=NULL;
 	double* y=NULL;
-	SeqVec<double>* in_nod=NULL;
+	double* in_nod=NULL;
 
 	/*recover handle and gate: */
Index: /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 15396)
@@ -4,5 +4,5 @@
 #include "./ContourToNodesx.h"
 
-int ContourToNodesx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, Contour<IssmPDouble>** contours,int numcontours,int edgevalue){
+int ContourToNodesx(IssmPDouble** pflags,double* x, double* y, int nods, Contour<IssmPDouble>** contours,int numcontours,int edgevalue){
 
 	int i;
@@ -15,6 +15,6 @@
 
 	/*output: */
-	SeqVec<IssmPDouble>* flags=NULL;
-	flags=new SeqVec<IssmPDouble>(nods);
+	IssmPDouble* flags=NULL;
+	flags=xNew<IssmPDouble>(nods);
 
 	/*Loop through all contours: */
@@ -27,7 +27,4 @@
 	}
 
-	/*Assemble vector: */
-	flags->Assemble();
-
 	/*Assign output pointers: */
 	*pflags=flags;
@@ -35,5 +32,5 @@
 }
 
-int ContourToNodesx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, DataSet* contours, int edgevalue){
+int ContourToNodesx(IssmPDouble** pflags,double* x, double* y, int nods, Contours* contours, int edgevalue){
 
 	/*Contour:*/
@@ -43,6 +40,6 @@
 
 	/*output: */
-	SeqVec<IssmPDouble>* flags=NULL;
-	flags=new SeqVec<IssmPDouble>(nods);
+	IssmPDouble* flags=NULL;
+	flags=xNewZeroInit<IssmPDouble>(nods);
 
 	/*Loop through all contours: */
@@ -54,7 +51,4 @@
 	}
 
-	/*Assemble vector: */
-	flags->Assemble();
-
 	/*Assign output pointers: */
 	*pflags=flags;
Index: /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.h
===================================================================
--- /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.h	(revision 15396)
@@ -7,9 +7,9 @@
 
 #include "../../shared/shared.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-int ContourToNodesx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, Contour<IssmPDouble>** contours,int numcontours,int edgevalue);
-int ContourToNodesx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, DataSet* contours, int edgevalue);
+int ContourToNodesx(IssmPDouble** pflags,double* x, double* y, int nods, Contour<IssmPDouble>** contours,int numcontours,int edgevalue);
+int ContourToNodesx(IssmPDouble** pflags,double* x, double* y, int nods, Contours* contours, int edgevalue);
 
 #endif /* _CONTOURTONODESX_H */
Index: /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./ControlInputGetGradientx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void ControlInputGetGradientx( Vector<IssmDouble>** pgradient, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
Index: /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h	(revision 15396)
@@ -5,6 +5,5 @@
 #define _CONTROLINPUTGETGRADIENTX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 void	ControlInputGetGradientx( Vector<IssmDouble>** pgradient, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
Index: /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./ControlInputScaleGradientx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* norm_list,int step){
Index: /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h	(revision 15396)
@@ -5,6 +5,5 @@
 #define _CONTROLINPUTSSCALEGRADIENTX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 void	ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* norm_list,int step);
Index: /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./ControlInputSetGradientx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* gradient){
Index: /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 15396)
@@ -5,6 +5,5 @@
 #define _CONTROLINPUTSSETGRADIENTX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* gradient);
Index: /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp	(revision 15396)
@@ -6,7 +6,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void CreateNodalConstraintsx( Vector<IssmDouble>** pys, Nodes* nodes,int configuration_type){
@@ -16,8 +14,12 @@
 	/*output: */
 	Vector<IssmDouble>* ys=NULL;
+	int ssize;
+	int slocalsize;
+
+	if(VerboseModule()) _printf0_("   Create nodal constraints\n");
 
 	/*figure out how many dofs we have: */
-	int ssize=nodes->NumberOfDofs(configuration_type,SsetEnum);
-	int slocalsize = nodes->NumberOfDofsLocal(configuration_type,SsetEnum);
+	ssize=nodes->NumberOfDofs(configuration_type,SsetEnum);
+	slocalsize = nodes->NumberOfDofsLocal(configuration_type,SsetEnum);
 
 	/*allocate:*/
Index: /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h	(revision 15396)
@@ -5,6 +5,5 @@
 #define _CREATENODALCONSTRAINTSX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp	(revision 15396)
@@ -5,8 +5,5 @@
 #include "./Delta18oParameterizationx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void Delta18oParameterizationx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters){
Index: /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.h
===================================================================
--- /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _DELTA18OPARAMETERIZATIONX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 15396)
@@ -6,9 +6,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
-void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
 
 	/*Intermediary*/
@@ -23,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->DragCoefficientAbsGradient(process_units,weight_index);
+		J+=element->DragCoefficientAbsGradient(weight_index);
 	}
 
Index: /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _DRAGCOEFFABSGRADX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/EdgeDetectionx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/EdgeDetectionx/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/modules/EdgeDetectionx/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,5 @@
+# Subdirectories {{{
+# }}}
+# Include Directory {{{
+include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/EdgeDetectionx)
+# }}}
Index: /issm/trunk/src/c/modules/EdgeDetectionx/EdgeDetectionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/EdgeDetectionx/EdgeDetectionx.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/EdgeDetectionx/EdgeDetectionx.cpp	(revision 15396)
@@ -0,0 +1,35 @@
+/*!\file EdgeDetectionx
+ * \brief: x code for EdgeDetection module
+ */
+
+/*Header files: {{{*/
+#include "./EdgeDetectionx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+/*}}}*/
+
+void EdgeDetectionx(Contours* contours, bool* image, int M, int N){
+
+	/*intermediary: */
+	int i;
+
+	_assert_(contours);
+
+	/*output: */
+	Contour<IssmPDouble>* contour=NULL;
+	IssmPDouble* x=NULL;
+	IssmPDouble* y=NULL;
+
+	/*Create bogus contour: */
+	x=xNewZeroInit<IssmPDouble>(10);
+	y=xNewZeroInit<IssmPDouble>(10);
+	for(i=0;i<10;i++){
+		x[i]=(IssmPDouble)i;
+		y[i]=(IssmPDouble)i;
+	}
+	contour= new Contour<IssmPDouble>(1,10,x,y,true);
+
+	/*Add contour to our dataset of contours: */
+	contours->AddObject(contour);
+
+}
Index: /issm/trunk/src/c/modules/EdgeDetectionx/EdgeDetectionx.h
===================================================================
--- /issm/trunk/src/c/modules/EdgeDetectionx/EdgeDetectionx.h	(revision 15396)
+++ /issm/trunk/src/c/modules/EdgeDetectionx/EdgeDetectionx.h	(revision 15396)
@@ -0,0 +1,14 @@
+/*!\file:  EdgeDetectionx.h
+ * \brief header file for EdgeDetectionx module
+ */ 
+
+#ifndef _EDGEDETECTIONX_H_
+#define _EDGEDETECTIONX_H_
+
+#include <string.h>
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void EdgeDetectionx(Contours* contours, bool* image, int M, int N);
+
+#endif  /* _EDGEDETECTIONX_H */
Index: /issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp	(revision 15396)
@@ -11,7 +11,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 int hascommondedge(int* element1,int* element2);
Index: /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 15396)
@@ -5,9 +5,6 @@
 #include "./Exp2Kmlx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
+#include "../../kml/kmlobjects.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../modules.h"
 
 int Exp2Kmlx(char* filexp,char* filkml,int sgn,bool holes){
@@ -50,13 +47,13 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_pprintString_("\nExp2Kmlx Module -- " << ctime(&time0));
+	_printf0_("\nExp2Kmlx Module -- " << ctime(&time0));
 
 	/*read exp file  */
 
-	if (!DomainOutlineRead(&nprof,&pnvert,&pprofx,&pprofy,&closed,filexp))
+	if (!ExpRead(&nprof,&pnvert,&pprofx,&pprofy,&closed,filexp))
 		_error_("Error reading exp file.");
-	_pprintLine_("Exp2Kmlx -- Reading " << nprof << " exp profiles from file \"" << filexp << "\".");
+	_printf0_("Exp2Kmlx -- Reading " << nprof << " exp profiles from file \"" << filexp << "\".\n");
 //	for (i=0; i<nprof; i++)
-//		_printLine_("i=" << i << "; nvert=" << pnvert[i] << ", closed=" << closed[i]);
+//		_printf_("i=" << i << "; nvert=" << pnvert[i] << ", closed=" << closed[i] << "\n");
 
 /*  construct kml file  */
@@ -121,5 +118,5 @@
 
 	if (holes && nprof && (pnvert[0] <= 1 || pprofx[0][pnvert[0]-1] != pprofx[0][0] || pprofy[0][pnvert[0]-1] != pprofy[0][0])) {
-		_pprintLine_("Warning -- Outer profile is not closed, so \"holes\" option will be ignored.");
+		_printf0_("Warning -- Outer profile is not closed, so \"holes\" option will be ignored.\n");
 		holes=false;
 	}
@@ -153,5 +150,5 @@
 		for (i=1; i<nprof; i++) {
 			if (pnvert[i] <= 1 || pprofx[i][pnvert[i]-1] != pprofx[i][0] || pprofy[i][pnvert[i]-1] != pprofy[i][0]) {
-				_pprintLine_("Warning -- Inner profile " << i+1 << " is not closed with \"holes\" specified, so it will be ignored.");
+				_printf0_("Warning -- Inner profile " << i+1 << " is not closed with \"holes\" specified, so it will be ignored.\n");
 				continue;
 			}
@@ -275,5 +272,5 @@
 /*  write kml file  */
 
-	_pprintLine_("Exp2Kmlx -- Writing kml document to file \"" << filkml << "\".");
+	_printf0_("Exp2Kmlx -- Writing kml document to file \"" << filkml << "\".\n");
 	fid=fopen(filkml,"w");
 	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
@@ -290,6 +287,5 @@
 	clock1=clock();
 	time1 =time(NULL);
-	_printf_(true,"Exp2Kmlx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
-			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+	_printf_("Exp2Kmlx Module -- " <<((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " <<difftime(time1,time0) << " elapsed seconds.\n\n\n");
 
 	return(iret);
Index: /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.h
===================================================================
--- /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 15396)
@@ -7,6 +7,5 @@
 
 #include <float.h>    /*  DBL_MAX  */
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./GetSolutionFromInputsx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void	GetSolutionFromInputsx( Vector<IssmDouble>** psolution, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters){
@@ -20,4 +18,6 @@
 	/*output: */
 	Vector<IssmDouble>* solution=NULL;
+
+	if(VerboseModule()) _printf0_("   Get solution from inputs\n");
 
 	/*retrive parameters: */
Index: /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _GETSOLUTIONFROMINPUTSXX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./GetVectorFromControlInputsx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void GetVectorFromControlInputsx(Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data){
@@ -48,5 +46,5 @@
 
 	/*Free ressources:*/
-	xdelete(&vec_vector);
+	delete vec_vector;
 
 	/*Assign output pointers:*/
Index: /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 15396)
@@ -5,6 +5,5 @@
 #define _GETVECTORFROMCONTROLINPUTSXX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./GetVectorFromInputsx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void GetVectorFromInputsx( Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
@@ -53,5 +51,5 @@
 
 	/*Free ressources:*/
-	xdelete(&vec_vector);
+	delete vec_vector;
 
 	/*Assign output pointers:*/
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 15396)
@@ -5,6 +5,5 @@
 #define _GETVECTORFROMINPUTSXX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/GiaDeflectionCorex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,8 @@
+# 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: /issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp	(revision 15396)
@@ -0,0 +1,171 @@
+/*!\file GiaDeflectionCorex
+ * \brief: GIA solution from Erik Ivins. 
+ * Compute deflection wi from a single disk of radius re, load history hes for 
+ * numtimes time steps. 
+ */
+
+#include "./GiaDeflectionCorex.h"
+
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../InputUpdateFromConstantx/InputUpdateFromConstantx.h"
+
+/*External blocks: {{{*/
+struct blockp{
+	double pset[7];
+};
+
+struct blocko{
+	double rhoi;
+};
+
+struct blockrad{
+	double distrad; 
+};
+
+struct blocks{
+	double aswokm_w; 
+	double aswokm_dwdt; 
+};
+
+extern "C" { 
+	int distme_(int* pNtime,int* pNtimp,int* pNtimm,double* time,double* bi,double* dmi,double* zhload);
+
+	int what0_(int* piedge,int* pNtimp,int* pNtimm,double* time,double* bi,double* dmi);
+	extern struct blockp blockp_;
+	extern struct blocko blocko_;
+	extern struct blockrad blockrad_;
+	extern struct blocks blocks_;
+}
+
+/*}}}*/
+
+void GiaDeflectionCorex( IssmDouble* pwi, IssmDouble* pdwidt, GiaDeflectionCoreArgs* arguments){
+
+	/*intermediary: */
+	int i;
+
+	/*output: */
+	IssmDouble wi=0;
+	IssmDouble dwidt=0;
+
+	/*inputs: {{{*/
+	/*constant: */
+	int idisk=1; // disk #
+	IssmDouble yts;
+
+	/*coming from the model structure, runtime configurable:*/
+	/*gia solution parameters: */
+	int iedge=0; 
+
+	/*gia inputs: */
+	IssmDouble ri; //radial distance from center of disk to vertex  i
+	IssmDouble re; //radius of disk
+	IssmDouble* hes; //loading history (in ice thickness)
+	IssmDouble* times; //loading history times
+	int numtimes; //loading history length
+	IssmDouble currenttime;
+	int Ntime; // number of times with load history 
+	int Ntimm; // Ntime-1 : for slope/y-cept of load segments 
+	int Ntimp; // Ntime+1 : for evaluation time  
+	IssmDouble* blockt_time=NULL;
+	IssmDouble* blockt_bi=NULL;
+	IssmDouble* blockt_dmi=NULL;
+	IssmDouble* blocky_zhload=NULL;
+
+	/*gia material parameters: */
+	IssmDouble lithosphere_shear_modulus;
+	IssmDouble lithosphere_density;
+	IssmDouble mantle_shear_modulus;
+	IssmDouble mantle_viscosity;
+	IssmDouble mantle_density;
+	IssmDouble lithosphere_thickness;
+
+	/*ice properties: */
+	IssmDouble rho_ice;
+
+	/*some debug info: */
+	int disk_id;
+
+/*}}}*/
+
+	/*Recover material parameters and loading history: see GiaDeflectionCoreArgs for more details {{{*/
+	ri=arguments->ri;
+	re=arguments->re;
+	hes=arguments->hes;
+	times=arguments->times;
+	numtimes=arguments->numtimes;
+	currenttime=arguments->currenttime;
+	lithosphere_shear_modulus=arguments->lithosphere_shear_modulus;
+	lithosphere_density=arguments->lithosphere_density;
+	mantle_shear_modulus=arguments->mantle_shear_modulus;
+	mantle_viscosity=arguments->mantle_viscosity;
+	mantle_density=arguments->mantle_density;
+	lithosphere_thickness=arguments->lithosphere_thickness;
+	rho_ice=arguments->rho_ice; 
+	disk_id=arguments->idisk;
+	iedge=arguments->iedge;
+	yts=arguments->yts;
+
+	/*}}}*/
+
+	/*Modify inputs to match naruse code: */
+	Ntime=numtimes;
+	Ntimm=Ntime-1;
+	Ntimp=Ntime+1;
+
+	/*Prepare block inputs for fortran distme and what0 routines of the naruse code: {{{*/
+	/*Now, let's set pset from the data that we got in input to GiaDeflectionCorex: */
+	blockp_.pset[0]=lithosphere_thickness;
+	blockp_.pset[1]=mantle_viscosity;
+	blockp_.pset[2]=lithosphere_shear_modulus;
+	blockp_.pset[3]=mantle_shear_modulus;
+	blockp_.pset[4]=lithosphere_density;
+	blockp_.pset[5]=mantle_density;
+	blockp_.pset[6]=re;
+	blocko_.rhoi=rho_ice; 
+
+	/*loading history: */
+	blocky_zhload=xNew<IssmDouble>(Ntime);
+	for(i=0;i<Ntime;i++){
+	blocky_zhload[i]=hes[i];
+	}
+
+	/*times in kyr: */
+	blockt_time=xNew<IssmDouble>(Ntimp);
+	for (i=0;i<Ntimp;i++){
+		blockt_time[i]=times[i]/1000.0/yts; 
+		if(i==numtimes-1)blockt_time[i]=times[numtimes-1]/1000.0/yts; // final loading time, same as evaluation time
+		if(i==numtimes)blockt_time[i]=times[numtimes-1]/1000.0/yts;   // evaluation time
+	}
+
+	/*bi: */
+	blockt_bi=xNew<IssmDouble>(Ntimm);
+
+	/*dmi: */
+	blockt_dmi=xNew<IssmDouble>(Ntimm);
+
+	/*radial distance of i-th element: */
+	blockrad_.distrad=ri/1000.0; // in km
+	/*}}}*/
+
+	/*Call distme driver: */
+	distme_(&Ntime,&Ntimp,&Ntimm,blockt_time,blockt_bi,blockt_dmi,blocky_zhload); 
+
+	/*Call what0 driver: */
+	what0_(&iedge,&Ntimp,&Ntimm,blockt_time,blockt_bi,blockt_dmi); 
+
+	/*output solution: */
+	wi = blocks_.aswokm_w;
+	dwidt = blocks_.aswokm_dwdt;
+	*pwi=wi;
+	*pdwidt=dwidt;
+
+	/*Free ressources: */
+	xDelete<IssmDouble>(blockt_time);
+	xDelete<IssmDouble>(blockt_bi);
+	xDelete<IssmDouble>(blockt_dmi);
+	xDelete<IssmDouble>(blocky_zhload);
+
+}
Index: /issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.h
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.h	(revision 15396)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.h	(revision 15396)
@@ -0,0 +1,13 @@
+/*!\file:  GiaDeflectionCorex.h
+ * \brief header file for ...
+ */ 
+
+#ifndef _GIADEFLECTIONCOREX_H
+#define _GIADEFLECTIONCOREX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void GiaDeflectionCorex( IssmDouble* pwi, IssmDouble* pdwidt, GiaDeflectionCoreArgs* arguments);
+
+#endif  /* _GIADEFLECTIONCOREX_H */
Index: /issm/trunk/src/c/modules/GiaDeflectionCorex/distme.f
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/distme.f	(revision 15396)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/distme.f	(revision 15396)
@@ -0,0 +1,73 @@
+      subroutine distme(Ntime,Ntimp,Ntimm,time,bi,dmi,zhload)
+      implicit double precision (a-h,o-y)
+      integer Ntime,Ntimp,Ntimm
+      parameter (Nafter=1)
+      double precision pset(7)
+      double precision time(Ntimp),dmi(Ntimm),bi(Ntimm),dumbt(Ntimp)
+      double precision hload(Ntime),qpat(Ntime),qt(Ntime)
+      double precision zhload(Ntime),rhoi,distrad
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      common /blockp/ pset
+      common /blockrad/ distrad 
+      common /blocko/ rhoi
+      data g /9.832186d0/, yearco /3.15576d7/, eradm/6.371d6/
+      data dpi /3.1415926535897932d0/, dzero/0.0d0/
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c The units of time(Ntimp) are ka and the height of the load in meters.
+c The slope, then for example, is in units of meters per ka.
+c Note that "dumbt( )" is designed to perserve the initial "time( )" variable.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 776 k = 1, Ntimp
+      dumbt(k) = time(k)
+  776 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 39 itime = 1, Ntime
+      hload(itime) = dble( zhload(itime) )
+   39 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c now set up a piece-wise history: bi() = y-intercept 
+c                                 dmi() = slope 
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 70 i = 2, Ntime
+      dmi(i-1) = ( hload(i) - hload(i-1) )/( dumbt(i)  - dumbt(i-1) )
+      bi(i-1) = hload(i-1) - ( dmi(i)*dumbt(i-1) )  
+   70 continue
+c      write(6,*) zhload(1,1), zhload(1,2) 
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c With pset(6) in mks units, lets convert the piecewise linear formulas
+c for the time-dependent ice load heights to dimensionless values w.r.t. time.
+c (tfact is in seconds)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      tfact = pset(2)/pset(4)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c get all times as dimensionless 
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 20 jt = 1, Nafter
+      time(Ntime + jt) = ( dumbt(Ntime + jt) * yearco * 1.0d3 ) / tfact
+   20 continue
+      do 75 ind = 1, Ntimm 
+      dmi(ind) =  dmi(ind) / (( yearco * 1.0d3 ) / tfact )
+   75 continue
+      do 77 j = 1, Ntime 
+      time(j) = ( dumbt(j) * yearco * 1.0d3 ) / tfact
+   77 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c create an incremental load in Pa and non-dimensionalized:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 80 iq = 1, Ntime
+      qpat(iq) = hload(iq)*rhoi*g
+      qt(iq) = qpat(iq) / pset(4)
+   80 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c As the final step in this routine, create a dimensionless stress load from
+c qp.  Here we'll use bi( ) and dmi( ) vectors with dimensionless time.  Then
+c qp (and it's piece-wise decomposition) is ready for the direct dimensionless
+c integrals for the inverse Laplace transform and inverse Hankel transform
+c without further mutiplicative factors.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 85 i = 2, Ntime
+      dmi(i-1) = ( qt(i) - qt(i-1) )/( time(i)  - time(i-1) )
+      bi(i-1) = qt(i-1) - ( dmi(i-1)*time(i-1) )  
+   85 continue
+  999 return
+      end
Index: /issm/trunk/src/c/modules/GiaDeflectionCorex/freed.f
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/freed.f	(revision 15396)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/freed.f	(revision 15396)
@@ -0,0 +1,222 @@
+      subroutine freed(r2,u2,r1,u1,h,zk,e1,e2,e4,b0,b1,a2,a1,a0,decay
+     1,amps)        
+      implicit double precision (a-h,o-z)
+      double precision decay(2),amps(5)
+      double precision ac0,ac1,ac2,ac3,ac4,ac5,ac6,ac7,ac8,ac9,ac10,
+     1ac11
+      common /blockz/ zkp
+      data zero /0.0d0/, g /9.832186d0/
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c Given the inputs to this subroutine(r2 through zk in the call
+c statement above), the outputs are coefficients of "s" that
+c are crucial to the Laplace transform inversion. From b0 and b1
+c we can compute the decay poles (or eigenvalues).    
+c 
+c  This is NOT true in our case, though. - SA
+c  NOTE IN THE CODE THAT A CALL TO THIS SUBROUTINE NEED NOT
+c  BE MADE AT EACH TIME STEP --- BUT WILL HAVE TO BE CALLED
+c  IN THE NUMERICAL INTEGRATION FOR COMPUTING THE INVERSE HANKEL
+c  TRANSFORM  ****
+c
+c Each term should be returned as dimensionless 
+c h => length   u2 => stress     taumx2 => time
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      zkp2 = zkp*zkp
+      ur = u1/u2
+      ghu2 = (g*h) / u2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac0 dimensional units are stress times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac0 = 4.0d0*ur*zkp2*( 1.0d0 + e4 +
+     1    2.0d0*e2*(1.0d0 + 2.0d0*zkp2) )
+c    DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac1 dimensional units are stress times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac1 = 2.0d0*r1*ghu2*zkp*(1.0d0 - e4 + 4.0d0*zkp*e2)
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac2 dimensional units are stress^2 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac2 = 8.0d0*ur*ur*(-1.0d0 + e1)*
+     1                     (1.0d0 + e1)*(1.0d0 + e2)*zkp2
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac3  dimensional units are stress^2 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac3 =
+     1   2.0d0*zkp*ghu2*ur*((r1 + r2)*(1.0d0 + e4) + 
+     2       2.0d0*(r2 - r1)*e2*( 1.0d0 + 2.0d0*zkp2 ))
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac4 dimensional units are stress^2 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac4 = ghu2*ghu2*r1*(r2 - r1)*
+     1      (1.0d0 - e4 + 4.0d0*zkp*e2)
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac5 dimensional units are stress^3 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac5 = 
+     1    4.0d0*zkp2*ur*ur*ur*(1.0d0 - e2 - 2.0d0*e1*zkp)*
+     2                (1.0d0 - e2 + 2.0d0*e1*zkp)
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac6 dimensional units are stress^3 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac6 =
+     1   2.0d0*zkp*ur*ur*(1.0d0 - e4
+     2               - 4.0d0*e2*zkp)*ghu2*r2
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac7 dimensional units are stress^3 times l^-2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac7 =
+     1 ur * ( ( (1.0d0 - e1)*(1.0d0 + e1) )**2)*r1*(r2 - r1)
+     2 * ( ghu2*ghu2 )
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac8 dimensional units are stress^0 times l^-1
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac8 = -2.0d0*zkp*(1.0d0 + e2*(1.0d0 + 2.0d0*zkp*(1.0d0 + zkp))) 
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac9 dimensional units are stress^1 times l^-1
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac9 = 
+     1  ( 4.0d0*zkp*u1 -
+     2 g*h*(r2 - r1)*(1.0d0 + e2*(1.0d0 + 2.0d0*zkp*(1.0d0 + zkp)))
+     3    ) / u2
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac10 dimensional units are stress^2 times l^-1
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac10 =
+     1   -2.0d0*zkp*ur*ur*( 1.0d0 - e2
+     2  - 2.0d0*zkp*e2*(1.0d0 + zkp) )
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c ac11 dimensional units are stress^2 times l^-1
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      ac11 =
+     1 ghu2*ur*(r2 - r1)*(1.0d0 - e2*(1.0d0 + 2.0d0*zkp))
+c     DIMESIONLESS
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c Other functions may be found in file "apcw0.record"
+c (Nov. 9 1996)
+c The following is a Mathematica version of the isolation of the
+c  coefficeints of the L transform variable s in the denominator.  
+c  Here is where the set-up is performed to obtain the "free decay"
+c  times (with the Hankel transform variable "zk" embedded.  Note that
+c  some greater efficency could be achieved by further simplifying the
+c  combinations of "acn" functions which are now a series of function
+c  subroutines in the fortran code.  The corresponding Mathematica
+c  session is "twolayer.Linversion" dated Nov. 23, 1996.
+c
+c In[59]:=
+c Together[%]
+c Out[59]=
+c    ac2 + ac3 - ac4 + 2 ac5 - 2 ac6 + 2 ac7
+c ---------------------------------------------
+c ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c In[61]:=
+c Simplify[Coefficient[els,s^2]]
+c Out[61]=
+c 1
+c In[65]:=
+c eslnos =
+c ac5/(ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7) - 
+c    ac6/(ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7) + 
+c 
+c   ac7/(ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7)
+c    
+c Out[65]=
+c                      ac5
+c --------------------------------------------- - 
+c ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c 
+c                        ac6
+c  --------------------------------------------- + 
+c   ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c 
+c                        ac7
+c  ---------------------------------------------
+c  ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c In[66]:=
+c Simplify[%]
+c Out[66]=
+c                ac5 - ac6 + ac7
+c ---------------------------------------------
+c ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c a common denominator factor is: bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      bc =  (   ac0 - ac1 +
+     1                     ac2 + ac3
+     2                                 - ac4 + ac5 -
+     3           ac6 + ac7  )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c b1: Denominator coefficent of s:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      b1 =
+     1  (  ac2 + ac3
+     2               - ac4 + ( 2.0d0 * ac5 )
+     3                                       - ( 2.0d0 * ac6 )
+     4                                       + ( 2.0d0 * ac7 )   ) / bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c b0: Denominator coefficent of s^0:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      b0 =
+     1 (  ac5 - ac6 +
+     2                 ac7  ) / bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c the eigenvaules are just the solution of the quadratic in s:
+c so return as "decay"
+c  *** Note that the decay times are defined as positive ***
+c      if a negative inverse decay time is returned there is an error!
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      sb1 = b1*b1
+      fb0 = 4.0d0*b0
+      diff =  sb1 - fb0          
+      if(diff.le.zero) go to 25
+      rs =  dsqrt( diff )          
+      decay(1) = -( - b1 - rs ) / 2.0d0
+      decay(2) = -( - b1 + rs ) / 2.0d0          
+      go to 26
+   25 idgen = 100
+      go to 9990
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c and for the numerator part of the quadratic s dependence
+c the Mathematica session is:
+c
+c Out[14]=
+c                                                                      2
+c ac10 + ac11 + (2 ac10 + 2 ac11 + ac9) s + (ac10 + ac11 + ac8 + ac9) s
+c----------------------------------------------------------------------
+c            ac0 - ac1 + ac2 + ac3 - ac4 + ac5 - ac6 + ac7
+c
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+   26 a0 = ( ac10 + ac11 ) / bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      a1 = ( 2.0d0*( ac10 + ac11 )
+     1                             + ac9 )  / bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      a2 =  (ac10 + ac11
+     1                   + ac8 + ac9) / bc
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c and the following terms are the amplitudes of the inverse Laplace
+c transform solution for the non-q part.  (See the boxed equation on
+c page 4 of the Nov. 23 1996 notes.)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      decdif = 1.0d0/(decay(2) - decay(1))
+      amps(1) = -decdif*( decay(1) * ( a1 - a2*decay(1) ) - a0 )
+      amps(2) =  decdif*( decay(2) * ( a1 - a2*decay(2) ) - a0 )
+      amps(3) = a2
+      amps(4) = - decay(1) * amps(1) 
+      amps(5) = - decay(2) * amps(2)
+      go to 999
+ 9990 write(6,998) idgen
+  998 format(' idgen val ** fatal error ** degenerate e.v.'/1h ,1p,1i12) 
+  999 return
+      end
Index: /issm/trunk/src/c/modules/GiaDeflectionCorex/ojrule.f
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/ojrule.f	(revision 15396)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/ojrule.f	(revision 15396)
@@ -0,0 +1,63 @@
+      subroutine ojrule(dk,bcin_w,bcin_dwdt)
+      implicit double precision(a-h,o-z)
+      parameter (nhank = 1024)
+      double precision yvalue_w(nhank),yvalue_dwdt(nhank)
+      double precision bcin_w(nhank),bcin_dwdt(nhank)
+      double precision wok_w,wok_dwdt,rpos
+      double precision swok_w,swok_dwdt
+      double precision pset(7)
+      double precision aswokm_w,aswokm_dwdt,distrad
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      common /blockrad/ distrad
+      common /blockp/ pset
+      common /blocks/ aswokm_w,aswokm_dwdt
+      data zero /0.0d0/, one /1.0d0/, two /2.0d0/, three /3.0d0/,
+     1rescal/ 1.0d0/
+      data yearco /3.15576d7/
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      bath = dk / three
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c rpos should be normalized wrt lithosphere thickness 
+c give r is normalized dist_rad :: r == dist_rad / h
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      r = distrad / (pset(1) / 1.0d3)
+      rpos = r 
+      ak = zero
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c form the yvalue's for the Simpson's rule formulas
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 425 ik = 1, nhank
+      ak = ak + dk
+      rak = ak * r
+      rarg = dbesj0( rak )
+      yvalue_w(ik) = bcin_w(ik) * rarg
+      yvalue_dwdt(ik) = bcin_dwdt(ik) * rarg
+  425 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c correct to end point val. in Simp. Rule
+c      yvalue(nhank) = bcin(nhank) * rarg / two
+c find the area under the curve using the Simpson's rule formulas
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      sumde_w = zero
+      sumde_dwdt = zero
+      do 300 int = 1, nhank
+      intp1 = int + 1
+      ide = 2 + ( (-1)**intp1 + 1 )
+      fide = dfloat(ide)
+      sumde_w = ( fide * yvalue_w(int) ) + sumde_w
+      sumde_dwdt = ( fide * yvalue_dwdt(int) ) + sumde_dwdt
+  300 continue
+      wok_w = bath * sumde_w
+      wok_dwdt = bath * sumde_dwdt
+      
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      hscale = sngl(pset(1))
+      hsckm = hscale / 1.0e3
+      swok_w = hscale * sngl(wok_w)
+      aswokm_w = swok_w
+      swok_dwdt = (hscale * yearco * 1.0e3 * sngl(wok_dwdt))
+     1                  * ( sngl(pset(4))/ sngl(pset(2)) )
+      aswokm_dwdt = swok_dwdt
+      return
+
+      end
Index: /issm/trunk/src/c/modules/GiaDeflectionCorex/pwise.f
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/pwise.f	(revision 15396)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/pwise.f	(revision 15396)
@@ -0,0 +1,42 @@
+      subroutine pwise(t,ta,tb,xi1,xi2,xi3,xi4,slope,ycept,decay,
+     1bhaq_w,bhaq_dwdt)
+      implicit double precision (a-h,o-z)
+      double precision decay(2)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c This subroutine retrieves the convolution for the ith linear piece-wise
+c q hat function (the load shape or Bessel function part having
+c been removed) with the free-decay solution. (see notes of
+c 12-31-96 "Convolution in time").  The convolution is returned as "bhaq".
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      tbt = tb - t
+      tat = ta - t
+      gat1 = tat * decay(1)
+      gat2 = tat * decay(2)
+      gbt1 = tbt * decay(1)
+      gbt2 = tbt * decay(2)
+      ea1 = dexp(gat1)
+      ea2 = dexp(gat2)
+      eb1 = dexp(gbt1)
+      eb2 = dexp(gbt2)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c define xit1 term:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit1 =(ycept/decay(1)) * (eb1 - ea1) -
+     1(slope/(decay(1)*decay(1))) *
+     2                            ( (1.0d0 - tb*decay(1))*eb1 
+     3                            - (1.0d0 - ta*decay(1))*ea1 )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c define xit2 term:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit2 =(ycept/decay(2)) * (eb2 - ea2) -
+     1(slope/(decay(2)*decay(2))) *
+     2                            ( (1.0d0 - tb*decay(2))*eb2 
+     3                            - (1.0d0 - ta*decay(2))*ea2 )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c add terms for the i-th interval contribution. 
+c ABOVE IS THE NON-DEGENERATE CASE
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      bhaq_w = (xi1 * xit1) + (xi2 * xit2)    
+      bhaq_dwdt = (xi3 * xit1) + (xi4 * xit2)    
+      return
+      end
Index: /issm/trunk/src/c/modules/GiaDeflectionCorex/qwise.f
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/qwise.f	(revision 15396)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/qwise.f	(revision 15396)
@@ -0,0 +1,65 @@
+      subroutine qwise(t,ta,qjadon,xi0,xi1,xi2,xi3,xi4,slope,ycept,
+     1decay,bhaq_w,bhaq_dwdt)
+      implicit double precision (a-h,o-z)
+      double precision decay(2)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c This subroutine retrieves the convolution for the J-th linear piece-wise
+c q hat function (the load shape or Bessel function part having been removed)
+c with the free-decay solution. (see notes of 3-27-97 "convo.ice" Mathematica
+c session).  The convolution is returned as "bhaq".
+c
+c  THIS ROUTINE REPLACES pwise.f ONLY FOR t <  time(Ntime) *
+c  (such that the load is still in place at time t).       *
+c
+c Note irate = 1 case has to be applied to the linear term only (freed.f applies
+c this correction to exponential terms)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xg1 = xi1/(decay(1)*decay(1))
+      xg2 = xi2/(decay(2)*decay(2))
+      xg3 = xi3/(decay(1)*decay(1))
+      xg4 = xi4/(decay(2)*decay(2))
+      gb1 = decay(1)*ycept
+      gb2 = decay(2)*ycept
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c define xit0 term:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit0_w = (xi0 + qjadon) * ( ( slope * t ) + ycept )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c define xit1 term:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit1_w = xg1 * (
+     1              gb1 + slope * ( ( t * decay(1) ) - 1.0d0 )
+     2          - ( gb1 + slope * ( ( ta * decay(1) ) - 1.0d0 ))
+     3                                   * dexp( decay(1) * (ta - t) )
+     4                       )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c define xit2 term:
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit2_w = xg2 * (
+     1              gb2 + slope * ( ( t * decay(2) ) - 1.0d0 )
+     2          - ( gb2 + slope * ( ( ta * decay(2) ) - 1.0d0 ) )
+     3                                   * dexp( decay(2) * (ta - t) )
+     4                       )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c And the rate equivalents:
+c (sign switch due to freed.f already
+c having corrected in x1t, x2t pass).
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      xit0_dwdt = (xi0 + qjadon) * slope 
+      xit1_dwdt =-xg3 * (
+     1              slope  
+     2     + ( gb1 + slope * ( ( ta * decay(1) ) - 1.0d0 ))
+     3                                   * dexp( decay(1) * (ta - t) )
+     4                       )
+      xit2_dwdt =-xg4 * (
+     1              slope 
+     2     + ( gb2 + slope * ( ( ta * decay(2) ) - 1.0d0 ))
+     3                                   * dexp( decay(2) * (ta - t) )
+     4                       )
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c add terms for the J-th (and final) interval contribution.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      bhaq_w = xit0_w + xit1_w + xit2_w
+      bhaq_dwdt = xit0_dwdt + xit1_dwdt + xit2_dwdt
+      return
+      end
Index: /issm/trunk/src/c/modules/GiaDeflectionCorex/stot.f
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/stot.f	(revision 15396)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/stot.f	(revision 15396)
@@ -0,0 +1,79 @@
+      subroutine stot(ikval,qjadon,fltng_w,fltng_dwdt,Ntimp,Ntimm,
+     1time,bi,dmi)
+      implicit double precision (a-h,o-z)
+      integer Ntimp,Ntimm
+      parameter (Nafter = 1)
+      parameter (nhank = 1024)
+      double precision decay(2)
+      double precision pset(7)
+      double precision time(Ntimp),bi(Ntimm),dmi(Ntimm)
+      double precision dekay1(nhank),dekay2(nhank),amp0(nhank),
+     1amp1(nhank),amp2(nhank),amp3(nhank),amp4(nhank)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      common /blockm/ dekay1,dekay2,amp0,amp1,amp2,amp3,amp4
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c  This subroutine returns the inverse Laplace transform to the
+c  time-domain for the vertical displacement at time t for Hankel wavenumber
+c  ikval.  (In general this routine needs to be called nhank times).
+c  The main derivation uses the Faltung theorem of Laplace transforms.
+c  (1-1-97)  NEW CASE OF 3-27-97 IS FOR t(Ntime + i) < t(Ntime) OR IN OTHER
+c  WORDS, THE LOAD STILL IN PLACE AT t.  OPTION CALL to qwise.f
+c  PERFORMS THIS. 
+c 
+c  A theory for the degenerate case was worked out but has been removed
+c  as an option from this code.
+c
+c  Definition of tspan: nondimensional time span backwards form present
+c                       when this routine is first called the dimensional
+c                       equivalent might be say tspan = 12 ka, then 11 and
+c                       then finally tspan = 0.
+c  Additional note for r.s.l calculations: the routines qwise and pwise
+c  are identical to the previous case for computations of present-day only
+c  vertical deformation field.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      decay(1) = dekay1(ikval)
+      decay(2) = dekay2(ikval)
+      xi0 = amp0(ikval)
+      xi1 = amp1(ikval)
+      xi2 = amp2(ikval)
+      xi3 = amp3(ikval)
+      xi4 = amp4(ikval)
+
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c note that tspan must be updated in the calling routine "what0.f"
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      t = time(Ntimp)
+      sumb_w = 0.0d0
+      sumb_dwdt = 0.0d0
+      ta = time(1)
+      tb = time(2)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      do 97 i = 1,Ntimm
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c note that this "if" prevents adding load
+c segments of "future" times when computing
+c an r.s.l. history (10-06-98).
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      if(t.lt.ta) go to 97
+      slope=dmi(i)
+      ycept=bi(i)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      if( t . gt . ta . and . t . le . tb) go to 38
+      call pwise(t,ta,tb,xi1,xi2,xi3,xi4,slope,ycept,decay,
+     1bhaq_w,bhaq_dwdt)
+      go to 39
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c Note that qwise is employed only for the J-th Q hat term when t for
+c evaluation still has to consider the load itself
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+   38 call qwise(t,ta,qjadon,xi0,xi1,xi2,xi3,xi4,slope,ycept,decay,
+     1bhaq_w,bhaq_dwdt)
+   39 sumb_w = bhaq_w + sumb_w
+      sumb_dwdt = bhaq_dwdt + sumb_dwdt
+      ta = time(i + 1)
+      tb = time(i + 2)
+   97 continue
+      fltng_w = sumb_w
+      fltng_dwdt = sumb_dwdt
+      return
+      end
Index: /issm/trunk/src/c/modules/GiaDeflectionCorex/what0.f
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/what0.f	(revision 15396)
+++ /issm/trunk/src/c/modules/GiaDeflectionCorex/what0.f	(revision 15396)
@@ -0,0 +1,127 @@
+      subroutine what0(iedge,Ntimp,Ntimm,time,bi,dmi)
+      implicit double precision (a-h,o-z)
+      integer Ntimp,Ntimm
+      parameter (nhank = 1024)
+      parameter (N = nhank/2)
+      double precision dekay1(nhank),dekay2(nhank),amp0(nhank),
+     1amp1(nhank),amp2(nhank),amp3(nhank),amp4(nhank),
+     1zksam(nhank),zksamp(nhank)
+      double precision decay(2),pset(7),amps(5),
+     1decta(2),dyri1(nhank),dyri2(nhank),sna(nhank)
+      double precision cinner_w(nhank),cinner_dwdt(nhank)
+      double precision bcin_w(nhank),bcin_dwdt(nhank)
+      double precision time(Ntimp),bi(Ntimm),dmi(Ntimm)
+      integer maxk
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      common /blockp/ pset
+      common /blockz/ zkp
+      common /blockm/ dekay1,dekay2,amp0,amp1,amp2,amp3,amp4
+      data yearco /3.15576d7/, pi /3.1415926535897932384d0/
+      data g /9.832186d0/, four /4.d0/, two /2.0d0/,
+     1 one /1.0d0/, zero/0.0d0/ , maxk/64/
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      twopi = two * pi
+      r2 = pset(6)
+      u2 = pset(4)
+      r1 = pset(5)
+      u1 = pset(3)
+      h  = pset(1)
+      urat = u1/u2
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c  alphap is dimensionless disk radius
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      alphap = pset(7)/pset(1)
+      twoap = two * alphap
+      rghm = ( r1 * g * h * alphap ) / (two * u2)
+      taumx = pset(2)/pset(4)
+      tmxyr = taumx / yearco
+c
+      dfac = dfloat(nhank)/dfloat(maxk)
+      endk = dfloat(nhank)/dfac
+      dk = endk/dfloat(nhank)
+c
+      ak = zero
+      do 7000 ik = 1,nhank
+      ak = ak + dk
+      zkp = ak
+      pikn = (6.371d6 * zkp) / h
+      zkd = pikn / 6.371d6
+c
+      zkp2 = 2.0d0 * zkp
+      zkp4 = 4.0d0 * zkp
+      e1 = dexp(zkp)
+      e2 = dexp(zkp2)
+      e4 = dexp(zkp4)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      call freed(r2,u2,r1,u1,h,zkd,e1,e2,e4,b0,b1,a2,a1,a0,decay,amps)
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      decta(1) = decay(1)/tmxyr
+      decta(2) = decay(2)/tmxyr
+      dyri1(ik) = decta(1)
+      dyri2(ik) = decta(2)
+      sna(ik) = pikn
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c Form vectors for full construction in pwise.f and stot.f
+c Note that freed will produce decay spectra defined as positive, 
+c ie. negative decay must reinsert a minus sign.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      dekay1(ik) = decay(1)
+      dekay2(ik) = decay(2)
+      amp0(ik) = amps(3)  
+      amp1(ik) = amps(1)  
+      amp2(ik) = amps(2)  
+      amp3(ik) = amps(4)  
+      amp4(ik) = amps(5)  
+      zksam(ik) = zkd
+      zksamp(ik) = zkp
+ 7000 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c The following looped call sets up the free solution convolved with the
+c load function q hat.  Note that the returned vector set "cinner" is the
+c inner-most part of the arguement of the inverse Hankel trans. integral.
+c It is time-dependent and the loop is for the k-dependancy. The time for
+c calculation is given in the vector "time(Ntimp)" in the routine stot.f that is
+c called below. Note that the sign on cinner(ik) below is for a load directed
+c downward.   ** For iedge = 1 assume sq. edge load and for iedge = 2 assume an
+c elliptical cross section.  Note loops 8500,8000 and 9500,9000 for the two
+c cases, respectively.
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+   49 go to (8499,9499), iedge
+ 8499 do 8000 ik = 1, nhank
+      xakap = zksamp(ik)*alphap
+      diku = xakap * urat
+      pref = diku / ( diku + rghm )
+      qjadon = one / ( four * zksamp(ik) * urat )
+      call stot(ik,qjadon,fltng_w,fltng_dwdt,Ntimp,Ntimm,time,bi,dmi)
+      cinner_w(ik) = - fltng_w * pref * twoap
+      cinner_dwdt(ik) = - fltng_dwdt * pref * twoap
+      bcin_w(ik) = cinner_w(ik) * dbesj1(xakap)
+      bcin_dwdt(ik) = cinner_dwdt(ik) * dbesj1(xakap)
+ 8000 continue
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+c "ojrule.f" computes the inverse Hankel trasform with a simple
+c Simpson's rule.  The routine "ojrule" is buliding a set of solutions stored
+c in common "blocks" in r or "asrpos(nrv) ", and computed rate or displacement
+c for each of N3G disks in "aswokm(nrv,N3G)" . 
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+      call ojrule(dk,bcin_w,bcin_dwdt)
+      go to 999
+c ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+ 9499 do 9000 ik = 1, nhank
+      xakap = zksamp(ik)*alphap
+      oxakap = one/xakap
+      diku = xakap * urat
+      pref = diku / ( diku + rghm )
+      qjadon = one / ( four * zksamp(ik) * urat )
+      call stot(ik,qjadon,fltng_w,fltng_dwdt,Ntimp,Ntimm,time,bi,dmi)
+      cinner_w(ik) = - fltng_w * pref * twoap
+      cinner_dwdt(ik) = - fltng_dwdt * pref * twoap
+      bcin_w(ik) = cinner_w(ik) * oxakap * ( dsin(xakap) * oxakap
+     1 - dcos(xakap) )
+      bcin_dwdt(ik) = cinner_dwdt(ik) * oxakap * ( dsin(xakap) * oxakap
+     1 - dcos(xakap) )
+ 9000 continue
+      call ojrule(dk,bcin_w,bcin_dwdt)
+  999 return
+
+      end
Index: /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 15396)
@@ -4,9 +4,6 @@
 
 #include "./Gradjx.h"
-#include "../modules.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void Gradjx(Vector<IssmDouble>** pgradient,IssmDouble** pnorm_list, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
@@ -49,5 +46,5 @@
 	for(i=0;i<num_controls;i++){
 		gradient->AXPY(gradient_list[i],1.0);
-		xdelete(&gradient_list[i]);
+		delete gradient_list[i];
 	}
 
Index: /issm/trunk/src/c/modules/Gradjx/Gradjx.h
===================================================================
--- /issm/trunk/src/c/modules/Gradjx/Gradjx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Gradjx/Gradjx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _GRADJX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 15396)
@@ -4,21 +4,18 @@
 
 #include "../../shared/shared.h"
-#include "../../io/io.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 #include "./GroundinglineMigrationx.h"
 
 void GroundinglineMigrationx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters){
 
-	int      i, migration_style,analysis_type;
-	IssmDouble*  vertices_potentially_ungrounding = NULL;
-	IssmDouble*  vertices_ungrounding             = NULL;
-	IssmDouble*  old_floatingice                  = NULL;
-	Vector<IssmDouble>*      vec_old_floatingice              = NULL;
-	Element* element                          = NULL;
+	int                 migration_style,analysis_type;
+	IssmDouble         *vertices_potentially_ungrounding = NULL;
+	IssmDouble         *vertices_ungrounding             = NULL;
+	IssmDouble         *old_floatingice                  = NULL;
+	Vector<IssmDouble> *vec_old_floatingice              = NULL;
+	Element            *element                          = NULL;
 
-	if(VerboseModule()) _pprintLine_("   Migrating grounding line");
+	if(VerboseModule()) _printf0_("   Migrating grounding line\n");
 
 	/*retrieve parameters: */
@@ -27,9 +24,17 @@
 
 	if(migration_style==NoneEnum) return;
-	if(migration_style!=AgressiveMigrationEnum && migration_style!=SoftMigrationEnum) _error_(EnumToStringx(migration_style) << " not supported yet!");
+
+	if(migration_style!=AgressiveMigrationEnum  &&
+		migration_style!=SoftMigrationEnum       &&
+		migration_style!=SubelementMigrationEnum &&
+		migration_style!=SubelementMigration2Enum)
+	 _error_("Grounding line migration "<<EnumToStringx(migration_style) << " not supported yet!");
+
+	/*Set toolkit to default*/
+	ToolkitsOptionsFromAnalysis(parameters,NoneAnalysisEnum);
 
 	if(migration_style==SoftMigrationEnum){
 		/*Create flag for grounded vertices above the hydrostatic equilibrium: */
-		vertices_potentially_ungrounding=PotentialSheetUngrounding(elements,vertices,parameters);
+		vertices_potentially_ungrounding=PotentialUngrounding(elements,vertices,parameters);
 
 		/*propagate ice shelf into connex areas of the ice sheet that potentially want to unground: */
@@ -42,5 +47,5 @@
 
 	/*Migrate grounding line : */
-	for(i=0;i<elements->Size();i++){
+	for(int i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->MigrateGroundingLine(old_floatingice,vertices_ungrounding);
@@ -48,5 +53,5 @@
 
 	/*free ressouces: */
-	xdelete(&vec_old_floatingice);
+	delete vec_old_floatingice;
 	xDelete<IssmDouble>(vertices_potentially_ungrounding);
 	xDelete<IssmDouble>(vertices_ungrounding);
@@ -81,6 +86,6 @@
 }
 /*%}}}*/
-/*FUNCTION PotentialSheetUngrounding {{{*/
-IssmDouble*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ 
+/*FUNCTION PotentialUngrounding {{{*/
+IssmDouble*    PotentialUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ 
 
 	int      i,numberofvertices;
@@ -96,5 +101,5 @@
 	for(i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->PotentialSheetUngrounding(vec_vertices_potentially_ungrounding);
+		element->PotentialUngrounding(vec_vertices_potentially_ungrounding);
 	}
 
@@ -104,5 +109,5 @@
 
 	/*free ressouces and return: */
-	xdelete(&vec_vertices_potentially_ungrounding);
+	delete vec_vertices_potentially_ungrounding;
 	return vertices_potentially_ungrounding;
 }
@@ -150,5 +155,5 @@
 			element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 			if(reCast<int,IssmDouble>(elements_neighboring_floatingce[element->Sid()])){
-				local_nflipped+=element->UpdatePotentialSheetUngrounding(vertices_potentially_ungrounding,vec_nodes_on_floatingice,nodes_on_floatingice);
+				local_nflipped+=element->UpdatePotentialUngrounding(vertices_potentially_ungrounding,vec_nodes_on_floatingice,nodes_on_floatingice);
 			}
 		}
@@ -157,5 +162,5 @@
 		#ifdef _HAVE_MPI_
 		MPI_Allreduce(&local_nflipped,&nflipped,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
-		if(VerboseConvergence()) _pprintLine_("   Additional number of vertices allowed to unground: " << nflipped);
+		if(VerboseConvergence()) _printf0_("   Additional number of vertices allowed to unground: " << nflipped << "\n");
 		#else
 		nflipped=local_nflipped;
@@ -167,10 +172,10 @@
 
 		/*Assemble and serialize:*/
-		xdelete(&vec_elements_neighboring_floatingice);
+		delete vec_elements_neighboring_floatingice;
 		nodes_on_floatingice=vec_nodes_on_floatingice->ToMPISerial();
 	}
 
 	/*Free ressources:*/
-	xdelete(&vec_nodes_on_floatingice);
+	delete vec_nodes_on_floatingice;
 	xDelete<IssmDouble>(elements_neighboring_floatingce);
 
Index: /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h
===================================================================
--- /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 15396)
@@ -14,6 +14,6 @@
 void       GroundinglineMigrationx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters);
 
-Vector<IssmDouble>*        CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type);
-IssmDouble*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,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);
 #endif  /* _GROUNDINGLINEMIGRATIONX_H */
Index: /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.cpp
===================================================================
--- /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.cpp	(revision 15396)
@@ -69,6 +69,6 @@
 			}
 		}
-		_printLine_( "" );
-		_printString_("Number of zeroes remaining: " << lines*samps-counter);
+		_printf_( ""  << "\n");
+		_printf_("Number of zeroes remaining: " << lines*samps-counter);
 		fflush( stdout );
 	#endif
@@ -88,6 +88,6 @@
 		}
 		//        n u m b e r   o f   z e r o e s   r e m a i n i n g :   1 2 3 4 5 6 7 8 9 10        
-		_printString_( "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" );
-		_printString_("Number of zeroes remaining: " << lines*samps-counter);
+		_printf_( "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" );
+		_printf_("Number of zeroes remaining: " << lines*samps-counter);
 		fflush( stdout );
 	#endif
@@ -97,5 +97,5 @@
 /***************** FIRST RUN *********************/
 /*
-fprintf ( stdout, "First  Application:  " ); time(&t2); _printString_( ctime(&t2) );
+fprintf ( stdout, "First  Application:  " ); time(&t2); _printf_( ctime(&t2) );
 */
 	for ( i = 0; i < lines; i++ ){
@@ -268,5 +268,5 @@
 
 			#ifdef _DEBUG2_
-				//_printLine_(temp << " " << elev << " " << range << " ");
+				//_printf_(temp << " " << elev << " " << range << " \n");
 			#endif
 
@@ -337,6 +337,6 @@
 
 	#ifdef _DEBUG2_
-		_printString_( "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" );
-		_printLine_("Number of zeroes remaining:          0\n");
+		_printf_( "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" );
+		_printf_("Number of zeroes remaining:          0\n\n");
 		printf ( "\n");
 	#endif
Index: /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./InputArtificialNoisex.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void InputArtificialNoisex( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int enum_name,IssmDouble min,IssmDouble max){
Index: /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h
===================================================================
--- /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _INPUTARTIFICIALNOISEX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 15396)
@@ -5,7 +5,6 @@
 #include "./InputControlUpdatex.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
+#include "../../classes/classes.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,IssmDouble scalar,bool save_parameter){
Index: /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.h
===================================================================
--- /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _INPUTCONTROLUPDATEX_H
 
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 15396)
@@ -5,7 +5,6 @@
 #include "./InputDuplicatex.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
+#include "../../classes/classes.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void InputDuplicatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int original_enum, int new_enum){
@@ -19,5 +18,5 @@
 	for(i=0;i<materials->Size();i++){
 		Material* material=(Material*)materials->GetObjectByOffset(i);
-		//material->InputDuplicate(original_enum,new_enum);
+		material->InputDuplicate(original_enum,new_enum);
 	}
 
Index: /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.h
===================================================================
--- /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _INPUTDUPLICATEX_H
 
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/InputScalex/InputScalex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputScalex/InputScalex.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputScalex/InputScalex.cpp	(revision 15396)
@@ -5,7 +5,6 @@
 #include "./InputScalex.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../classes/classes.h"
 
 void InputScalex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type, IssmDouble scale_factor){
Index: /issm/trunk/src/c/modules/InputScalex/InputScalex.h
===================================================================
--- /issm/trunk/src/c/modules/InputScalex/InputScalex.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputScalex/InputScalex.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _SCALEINPUTX_H
 
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/InputToResultx/InputToResultx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputToResultx/InputToResultx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputToResultx/InputToResultx.cpp	(revision 15396)
@@ -5,7 +5,6 @@
 #include "./InputToResultx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
+#include "../../classes/classes.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void InputToResultx(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type){
Index: /issm/trunk/src/c/modules/InputToResultx/InputToResultx.h
===================================================================
--- /issm/trunk/src/c/modules/InputToResultx/InputToResultx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputToResultx/InputToResultx.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _INPUTTORESULTX_H
 
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 15396)
@@ -5,11 +5,10 @@
 #include "./InputUpdateFromConstantx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool   constant, int name){
 
 	int i;
+	if(VerboseModule()) _printf0_("   Input updates from constant\n");
 
 	/*Elements and loads drive the update: */
@@ -32,4 +31,5 @@
 
 	int i;
+	if(VerboseModule()) _printf0_("   Input updates from constant\n");
 
 	/*Elements and loads drive the update: */
@@ -52,4 +52,5 @@
 
 	int i;
+	if(VerboseModule()) _printf0_("   Input updates from constant\n");
 
 	/*Elements and loads drive the update: */
Index: /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _UPDATEINPUTSFROMCONSTANTXX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 15396)
@@ -5,8 +5,8 @@
 #include "./InputUpdateFromDakotax.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../modules.h"
+#include "../InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h"
+#include "../InputUpdateFromConstantx/InputUpdateFromConstantx.h"
+#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){
Index: /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _INPUTUPDATEFROMDAKOTAXX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#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);
Index: /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 15396)
@@ -5,8 +5,6 @@
 #include "./InputUpdateFromMatrixDakotax.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../modules.h"
+#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){
Index: /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _UPDATEINPUTSFROMMATRIXDAKOTAXX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./InputUpdateFromSolutionx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* solution){
Index: /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _UPDATEINPUTSFROMSOLUTIONXX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./InputUpdateFromVectorDakotax.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* vector, int name, int type){
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _UPDATEINPUTSFROMVECTORDAKOTAXX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./InputUpdateFromVectorx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* vector, int name, int type){
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _UPDATEINPUTSFROMVECTORXX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 15396)
@@ -12,13 +12,12 @@
 #include "./InterpFromGridToMeshx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
+#include "../../shared/io/io.h"
 /*}}}*/
 
 /*InterpFromGridToMeshx{{{*/
-int InterpFromGridToMeshx(SeqVec<IssmPDouble>** pdata_mesh,double* x_in, int x_rows, double* y_in, int y_rows, double* data, int M, int N, double* x_mesh, double* y_mesh, int nods,double default_value, int interpenum){
+int InterpFromGridToMeshx(IssmSeqVec<IssmPDouble>** pdata_mesh,double* x_in, int x_rows, double* y_in, int y_rows, double* data, int M, int N, double* x_mesh, double* y_mesh, int nods,double default_value, int interpenum){
 
 	/*output: */
-	SeqVec<IssmPDouble>* data_mesh=NULL;
+	IssmSeqVec<IssmPDouble>* data_mesh=NULL;
 
 	/*Intermediary*/
@@ -46,5 +45,5 @@
 
 	/*Allocate output vector: */
-	data_mesh=new SeqVec<IssmPDouble>(nods);
+	data_mesh=new IssmSeqVec<IssmPDouble>(nods);
 
 	/*Find out what kind of coordinates (x_in,y_in) have been given is input*/
@@ -88,8 +87,9 @@
 	/*launch the thread manager with InterpFromGridToMeshxt as a core: */
 	LaunchThread(InterpFromGridToMeshxt,(void*)&gate,num);
-	_printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+	_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
 
 	/*Assign output pointers:*/
 	*pdata_mesh=data_mesh;
+	return 1;
 }
 /*}}}*/
@@ -126,5 +126,5 @@
 	double *y                     = gate->y;
 	int     nods                  = gate->nods;
-	SeqVec<IssmPDouble>*data_mesh = gate->data_mesh;
+	IssmSeqVec<IssmPDouble>*data_mesh = gate->data_mesh;
 	double *data                  = gate->data;
 	double  default_value         = gate->default_value;
@@ -141,5 +141,5 @@
 
 		if(debug && my_thread==0)
-		 _printString_("\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);
@@ -177,5 +177,5 @@
 					break;
 				default:
-					_printLine_("Interpolation " << EnumToStringx(interpenum) << " not supported yet");
+					_printf_("Interpolation " << EnumToStringx(interpenum) << " not supported yet\n");
 					return NULL; /*WARNING: no error because it would blow up the multithreading!*/
 			}
Index: /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h
===================================================================
--- /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h	(revision 15396)
@@ -6,7 +6,7 @@
 #define _INTERPFROMGRIDTOMESHX_H
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
 
 /*threading: */
@@ -24,8 +24,8 @@
 	double*             x_mesh;
 	double*             y_mesh;
-	SeqVec<IssmPDouble>* data_mesh;
+	IssmSeqVec<IssmPDouble>* data_mesh;
 } InterpFromGridToMeshxThreadStruct;
 
-int    InterpFromGridToMeshx(SeqVec<IssmPDouble>** pdata_mesh,double* x, int x_rows, double* y, int y_rows, double* data, int M, int N, double* x_mesh, double* y_mesh, int nods, double default_value, int interpenum=BilinearInterpEnum);
+int    InterpFromGridToMeshx(IssmSeqVec<IssmPDouble>** pdata_mesh,double* x, int x_rows, double* y, int y_rows, double* data, int M, int N, double* x_mesh, double* y_mesh, int nods, double default_value, int interpenum=BilinearInterpEnum);
 void*  InterpFromGridToMeshxt(void* vInterpFromGridToMeshxThreadStruct);
 bool   findindices(int* pn,int* pm,double* x,int x_rows, double* y,int y_rows, double xgrid,double ygrid);
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 15396)
@@ -5,10 +5,9 @@
 #include "./InterpFromMesh2dx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../classes/objects/objects.h"
-#include "../modules.h"
+#include "../../classes/classes.h"
+#include "../ContourToNodesx/ContourToNodesx.h"
 
-int InterpFromMesh2dx(SeqVec<IssmPDouble>** pdata_prime,
+int InterpFromMesh2dx(IssmSeqVec<IssmPDouble>** pdata_prime,
 			double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length,
 			double* x_prime, double* y_prime, int nods_prime,
@@ -16,5 +15,5 @@
 
 	/*Output*/
-	SeqVec<IssmPDouble>* data_prime=NULL;
+	IssmSeqVec<IssmPDouble>* data_prime=NULL;
 
 	/*Intermediary*/
@@ -26,5 +25,4 @@
 
 	/*contours: */
-	SeqVec<IssmPDouble> *vec_incontour = NULL;
 	double              *incontour     = NULL;
 
@@ -70,5 +68,5 @@
 
 	/*Initialize output*/
-	data_prime=new SeqVec<IssmPDouble>(nods_prime);
+	data_prime=new IssmSeqVec<IssmPDouble>(nods_prime);
 	if(num_default_values){
 		if(num_default_values==1)for (i=0;i<nods_prime;i++) data_prime->SetValue(i,default_values[0],INS_VAL);
@@ -78,6 +76,5 @@
 	/*Build indices of contour: */
 	if(numcontours){
-		ContourToNodesx( &vec_incontour,x_prime,y_prime,nods_prime,contours,numcontours,1);
-		incontour=vec_incontour->ToMPISerial();
+		ContourToNodesx( &incontour,x_prime,y_prime,nods_prime,contours,numcontours,1);
 	}
 	else{
@@ -112,3 +109,4 @@
 	 xDelete<double>(incontour);
 	*pdata_prime=data_prime;
+	return 1;
 }
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _INTERPFROMMESH2DX_H
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../toolkits/toolkits.h"
 
@@ -22,5 +22,5 @@
 	double              ymin,ymax;
 	int                 nods_prime;
-	SeqVec<IssmPDouble> *data_prime;
+	IssmSeqVec<IssmPDouble> *data_prime;
 	double              *x_prime;
 	double              *y_prime;
@@ -31,5 +31,5 @@
 } InterpFromMesh2dxThreadStruct;
 
-int InterpFromMesh2dx(SeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, int nods_prime,
+int InterpFromMesh2dx(IssmSeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, int nods_prime,
 		double* default_values,int num_default_values,Contour<IssmPDouble>** contours,int numcontours);
 
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 15396)
@@ -32,5 +32,5 @@
 	double  ymax                    = gate->ymax;
 	int     nods_prime              = gate->nods_prime;
-	SeqVec<IssmPDouble>* data_prime = gate->data_prime;
+	IssmSeqVec<IssmPDouble>* data_prime = gate->data_prime;
 	double *x_prime                 = gate->x_prime;
 	double *y_prime                 = gate->y_prime;
@@ -47,5 +47,5 @@
 		/*display current iteration*/
 		if (debug && my_thread==0 && fmod((double)i,(double)100)==0)
-		 _printString_("\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)
-	 _printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
 	return NULL;
 }
Index: /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 15396)
@@ -5,5 +5,4 @@
 #include "./InterpFromMeshToGridx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 
 void InterpFromMeshToGridx(double** px_m,double** py_m,double** pgriddata,double* index_mesh, double* x_mesh, double* y_mesh, int nods,int nels, double* data_mesh, int data_length, double xmin,double ymax,double xposting,double yposting,int nlines,int ncols,double default_value) {
@@ -20,5 +19,5 @@
 	bool   debug;
 	int    xflip,yflip;
-	double area,ymin;
+	double area;
 	double area_1,area_2,area_3;
 	double x_tria_min,y_tria_min;
@@ -52,4 +51,10 @@
 	debug=(bool)((double)ncols*nlines*nels >= 5*pow(10.,10.));
 
+	/*Initialize coordintes and griddata*/
+	for(i=0;i<nlines;i++){
+		for(j=0;j<ncols; j++){
+			griddata[i*ncols+j]=default_value;
+		}
+	}
 	/*figure out if x or y are flipped*/
 	if (xposting<0) xflip=1;
@@ -58,28 +63,26 @@
 	else yflip=0;
 
-	/*Compute coordinates lists*/
-	ymin=ymax-(nlines-1)*yposting;
-	for(i=0;i<nlines;i++)   y_grid[i]= ymin + yposting*i;
-	for(i=0;i<ncols; i++)   x_grid[i]= xmin + xposting*i;
 
-	/*Initialize coordintes and griddata*/
-	for(i=0;i<nlines;i++){
-		for(j=0;j<ncols; j++){
-			griddata[i*ncols+j]=default_value;
-		}
-	}
 
 	/*Get extreme coordinates of the grid*/
 	if (xflip){
-		x_grid_min=x_grid[ncols-1]; x_grid_max=x_grid[0];
+		for(i=0;i<ncols; i++) x_grid[ncols-1-i] = xmin - xposting*i;
+		x_grid_min=x_grid[ncols-1];
+		x_grid_max=x_grid[0];
 	}
 	else{
-		x_grid_min=x_grid[0]; x_grid_max=x_grid[ncols-1];
+		for(i=0;i<ncols; i++) x_grid[i]= xmin + xposting*i;
+		x_grid_min=x_grid[0];
+		x_grid_max=x_grid[ncols-1];
 	}
 	if (yflip){
-		y_grid_min=y_grid[nlines-1]; y_grid_max=y_grid[0];
+		for(i=0;i<nlines;i++) y_grid[i] = ymax + yposting*i;
+		y_grid_min=y_grid[nlines-1];
+		y_grid_max=y_grid[0];
 	}
 	else{
-		y_grid_min=y_grid[0]; y_grid_max=y_grid[nlines-1];
+		for(i=0;i<nlines;i++) y_grid[nlines-1-i]= ymax - yposting*i;
+		y_grid_min=y_grid[0];
+		y_grid_max=y_grid[nlines-1];
 	}
 
@@ -89,5 +92,5 @@
 		/*display current iteration*/
 		if (debug && fmod((double)n,(double)100)==0)
-		 _printString_("\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*/
@@ -169,5 +172,5 @@
 	}
 	if (debug)
-	 _printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
 
 	/*Assign output pointers:*/
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 15396)
@@ -5,8 +5,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../classes/objects/objects.h"
-#include "../modules.h"
+#include "../../classes/classes.h"
+#include "../../bamg/bamgobjects.h"
 
 using namespace bamg;
@@ -69,5 +68,5 @@
 	/*Loop over output nodes*/
 	for(i=0;i<N_interp;i++){
-		//if(i%100==0) _printString_("\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){
@@ -143,5 +142,5 @@
 		}
 	}
-	//if(N_interp>=100) _printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+	//if(N_interp>=100) _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
 
 	/*clean-up and return*/
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 15396)
@@ -5,10 +5,9 @@
 #include "./InterpFromMeshToMesh3dx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 
-int InterpFromMeshToMesh3dx( SeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, double* z_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, double* z_prime, int nods_prime,double default_value) {
+int InterpFromMeshToMesh3dx( IssmSeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, double* z_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, double* z_prime, int nods_prime,double default_value) {
 
 	/*Output*/
-	SeqVec<IssmPDouble>* data_prime=NULL;
+	IssmSeqVec<IssmPDouble>* data_prime=NULL;
 
 	/*Intermediary*/
@@ -54,5 +53,5 @@
 
 	/*Initialize output*/
-	data_prime=new SeqVec<IssmPDouble>(nods_prime);
+	data_prime=new IssmSeqVec<IssmPDouble>(nods_prime);
 	for (i=0;i<nods_prime;i++) data_prime->SetValue(i,default_value,INS_VAL);
 
@@ -62,5 +61,5 @@
 		/*display current iteration*/
 		if (debug && fmod((double)i,(double)100)==0)
-		 _printString_("\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*/
@@ -133,7 +132,8 @@
 	}
 	if (debug)
-	 _printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
 
 	/*Assign output pointers:*/
 	*pdata_prime=data_prime;
+	return 1;
 }
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h	(revision 15396)
@@ -7,7 +7,7 @@
 
 #include "../../toolkits/toolkits.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
-int InterpFromMeshToMesh3dx(SeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, double* z_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, double* z_prime, int nods_prime,double default_value);
+int InterpFromMeshToMesh3dx(IssmSeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, double* z_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, double* z_prime, int nods_prime,double default_value);
 
 #endif /* _INTERPFROMMESHTOMESH3DX_H */
Index: /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 15396)
@@ -5,8 +5,5 @@
 #include "./IoModelToConstraintsx.h"
 #include "../../shared/shared.h"
-#include "../../io/io.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type){
@@ -14,4 +11,5 @@
 	/*intermediary: */
 	int     i,j;
+	IssmDouble yts;
 	bool        transient        = false;
 	FILE       *fid              = NULL;
@@ -30,4 +28,5 @@
 	/*Fetch parameters: */
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&yts,ConstantsYtsEnum);
 
 	/*First of, find the record for the enum, and get code  of data type: */
@@ -67,8 +66,6 @@
 		times=xNew<IssmDouble>(N);
 		for(j=0;j<N;j++){
-			times[j]=IssmDoublevector[(M-1)*N+j];
+			times[j]=IssmDoublevector[(M-1)*N+j]*yts;
 		}
-		/*unit conversion: */
-		UnitConversion(times,N,ExtToIuEnum,TimeEnum);
 
 		/*Create constraints from x,y,z: */
Index: /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 15396)
@@ -5,6 +5,5 @@
 #define _IOMODEL_TO_CONSTRAINTS_H_
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.cpp
===================================================================
--- /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 15396)
@@ -4,8 +4,5 @@
 #include "./KMLFileReadx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 KML_Object* KMLFileReadx(FILE* fid){
@@ -21,5 +18,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_pprintString_("\nKMLFileReadx Module -- " << ctime(&time0));
+	_printf0_("\nKMLFileReadx Module -- " << ctime(&time0));
 
 /*  read kml file  */
@@ -43,15 +40,15 @@
 		}
 
-//		_pprintLine_(kstr);
+//		_printf0_(kstr << "\n");
 		xDelete<char>(kstr);
 	}
 
 	if (kxml) {
-		_pprintLine_("XML declaration:");
+		_printf0_("XML declaration:\n");
 		kxml->DeepEcho("  ");
 		delete kxml;
 	}
 	if (kdtd) {
-		_pprintLine_("DTD declaration (not yet implemented):");
+		_printf0_("DTD declaration (not yet implemented):\n");
 		kdtd->DeepEcho("  ");
 		delete kdtd;
@@ -60,6 +57,5 @@
 	clock1=clock();
 	time1 =time(NULL);
-	_printf_(true,"KMLFileReadx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
-			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+	_printf_("KMLFileReadx Module -- " <<((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " <<difftime(time1,time0) << " elapsed seconds.\n\n\n");
 
 	return(kfil);
Index: /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.h
===================================================================
--- /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.h	(revision 15396)
@@ -7,6 +7,5 @@
 
 #include <float.h>    /*  DBL_MAX  */
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../kml/kmlobjects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp
===================================================================
--- /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 15396)
@@ -4,8 +4,5 @@
 #include "./KMLMeshWritex.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void KMLMeshWritex(int* ierror,char* name,char* notes,int* elem,int melem,int nelem,int* nodecon,int mncon,int nncon,double* lat, double* lng,int* part,double* data, int mdata, int ndata,double* cmap, int mcmap, int ncmap,FILE* fid){
@@ -29,5 +26,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_pprintString_("\nKMLMeshWritex Module -- " << ctime(&time0));
+	_printf0_("\nKMLMeshWritex Module -- " << ctime(&time0));
 
 /*  construct kml document  */
@@ -83,5 +80,5 @@
 
 	if (cmap) {
-		_pprintLine_("Writing " << mcmap << " Matlab colors as KML style templates.");
+		_printf0_("Writing " << mcmap << " Matlab colors as KML style templates.\n");
 		ipt=0;
 		for (i=0; i<mcmap; i++) {
@@ -118,5 +115,5 @@
 
 	if (!nodecon) {
-		_pprintLine_("Creating the node connectivity table.");
+		_printf0_("Creating the node connectivity table.\n");
 		nncon=mxepg+1;
 		nodecon=xNewZeroInit<int>(mncon*nncon);
@@ -149,5 +146,5 @@
 
 		else if (mdata == mncon) {
-			_pprintLine_("Averaging nodal data to element data.");
+			_printf0_("Averaging nodal data to element data.\n");
 			edata=xNewZeroInit<double>(melem*ndata);
 			edfree=true;
@@ -188,10 +185,9 @@
 	clock0a=clock();
 	time0a =time(NULL);
-	_printf_(true,"  Constructed kml document -- %f CPU seconds; %f elapsed seconds.\n\n",
-			 ((double)(clock0a-clock0))/CLOCKS_PER_SEC,difftime(time0a,time0));
+	_printf_("  Constructed kml document -- " << ((double)(clock0a-clock0))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time0a,time0) << " elapsed seconds.\n\n\n");
 
 /*  write kml file  */
 
-	_pprintLine_("Writing kml document to file.");
+	_printf0_("Writing kml document to file.\n");
 	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
 	fprintf(fid,"<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n");
@@ -200,18 +196,15 @@
 	clock0b=clock();
 	time0b =time(NULL);
-	_printf_(true,"  Wrote kml file -- %f CPU seconds; %f elapsed seconds.\n\n",
-			 ((double)(clock0b-clock0a))/CLOCKS_PER_SEC,difftime(time0b,time0a));
-
-	_pprintLine_("Deleting kml document.");
+	_printf_("  Wrote kml file -- " << ((double)(clock0b-clock0a))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time0b,time0a) << " elapsed seconds.\n\n\n");
+
+	_printf0_("Deleting kml document.\n");
 	delete kdoc;
 	clock0c=clock();
 	time0c =time(NULL);
-	_printf_(true,"  Deleted kml document -- %f CPU seconds; %f elapsed seconds.\n\n",
-			 ((double)(clock0c-clock0b))/CLOCKS_PER_SEC,difftime(time0c,time0b));
+	_printf_("  Deleted kml document -- " << ((double)(clock0c-clock0b))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time0c,time0b) << " elapsed seconds.\n\n\n");
 
 	clock1=clock();
 	time1 =time(NULL);
-	_printf_(true,"KMLMeshWritex Module -- %f CPU seconds; %f elapsed seconds.\n\n",
-			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+	_printf_("KMLMeshWritex Module -- " << ((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time1,time0) << " elapsed seconds.\n\n\n");
 
 	return;
@@ -304,5 +297,5 @@
 /*  write each element as a polygon placemark  */
 
-	_pprintLine_("Writing " << melem << " tria elements as KML polygons.");
+	_printf0_("Writing " << melem << " tria elements as KML polygons.\n");
 
 	for (i=0; i<melem; i++) {
@@ -356,7 +349,7 @@
 
 //		if (!(int)fmod((double)(i+1),1000))
-//			_pprintLine_("  " << (i+1) << " tria elements written.");
+//			_printf0_("  " << (i+1) << " tria elements written.\n");
 	}
-	_pprintLine_("  " << melem << " tria elements written.");
+	_printf0_("  " << melem << " tria elements written.\n");
 
 	return(kfold);
Index: /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.h
===================================================================
--- /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.h	(revision 15395)
+++ /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.h	(revision 15396)
@@ -7,6 +7,5 @@
 
 #include <float.h>    /*  DBL_MAX  */
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../kml/kmlobjects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.cpp
===================================================================
--- /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.cpp	(revision 15396)
@@ -4,8 +4,6 @@
 #include "./KMLOverlayx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../kml/kmlobjects.h"
 
 void KMLOverlayx(int* ierror,
@@ -28,5 +26,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_pprintString_("\nKMLOverlayx Module -- " << ctime(&time0));
+	_printf0_("\nKMLOverlayx Module -- " << ctime(&time0));
 
 /*  construct kml file  */
@@ -81,5 +79,5 @@
 /*  write kml file  */
 
-	_pprintLine_("Writing kml document to file.");
+	_printf0_("Writing kml document to file.\n");
 	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
 	kfile->Write(fid,indent);
@@ -89,6 +87,5 @@
 	clock1=clock();
 	time1 =time(NULL);
-	_printf_(true,"KMLOverlayx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
-			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+	_printf_("KMLOverlayx Module -- " << ((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time1,time0) << " elapsed seconds.\n\n\n");
 
 	return;
Index: /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.h
===================================================================
--- /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.h	(revision 15396)
@@ -7,6 +7,5 @@
 
 #include <float.h>    /*  DBL_MAX  */
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 15396)
@@ -5,9 +5,6 @@
 #include "./Kml2Expx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../modules.h"
+#include "../KMLFileReadx/KMLFileReadx.h"
 
 int Kml2Expx(char* filkml,char* filexp,
@@ -38,5 +35,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_pprintString_("\nKml2Expx Module -- " << ctime(&time0));
+	_printf0_("\nKml2Expx Module -- " << ctime(&time0));
 
 /*  read kml file  */
@@ -49,5 +46,5 @@
 /*  open exp file  */
 
-	_pprintLine_("Writing exp profiles to file.");
+	_printf0_("Writing exp profiles to file.\n");
 	fido=fopen(filexp,"w");
 
@@ -64,6 +61,5 @@
 	clock1=clock();
 	time1 =time(NULL);
-	_printf_(true,"Kml2Expx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
-			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+	_printf_("Kml2Expx Module -- " << ((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time1,time0) << " elapsed seconds.\n\n\n");
 
 	return(iret);
Index: /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.h
===================================================================
--- /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.h	(revision 15396)
@@ -7,6 +7,5 @@
 
 #include <float.h>    /*  DBL_MAX  */
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 15396)
@@ -5,8 +5,6 @@
 #include "./Krigingx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../classes/objects/objects.h"
-#include "../../Container/Observations.h"
+#include "../../classes/classes.h"
 #include "../modules.h"
 #ifdef _HAVE_GSL_
@@ -85,8 +83,8 @@
 		observations->ObservationList(&x,&y,&data,&nobs);
 
-		_printLine_("Generation Delaunay Triangulation");
+		_printf_("Generation Delaunay Triangulation\n");
 		BamgTriangulatex(&index,&nel,x,y,nobs);
 
-		_printLine_("Interpolating");
+		_printf_("Interpolating\n");
 		xDelete<double>(predictions);
 		InterpFromMeshToMesh2dx(&predictions,index,x,y,nobs,nel,data,nobs,1,x_interp,y_interp,n_interp,options);
@@ -112,5 +110,5 @@
 		/*launch the thread manager with Krigingxt as a core: */
 		LaunchThread(NearestNeighbort,(void*)&gate,num);
-		_printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
 		xDelete<int>(gate.numdone);
 	}
@@ -134,5 +132,5 @@
 		/*launch the thread manager with Krigingxt as a core: */
 		LaunchThread(idwt,(void*)&gate,num);
-		_printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
 		xDelete<int>(gate.numdone);
 	}
@@ -156,5 +154,5 @@
 		/*launch the thread manager with Krigingxt as a core: */
 		LaunchThread(v4t,(void*)&gate,num);
-		_printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
 		xDelete<int>(gate.numdone);
 	}
@@ -179,5 +177,5 @@
 		/*launch the thread manager with Krigingxt as a core: */
 		LaunchThread(Krigingxt,(void*)&gate,num);
-		_printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
 		xDelete<int>(gate.numdone);
 	}
@@ -232,5 +230,5 @@
 			int alldone=numdone[0];
 			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
-			_printString_("\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.<<"%");
 		}
 
@@ -279,5 +277,5 @@
 			int alldone=numdone[0];
 			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
-			_printString_("\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.<<"%");
 		}
 
@@ -326,5 +324,5 @@
 			int alldone=numdone[0];
 			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
-			_printString_("\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.<<"%");
 		}
 
@@ -371,5 +369,5 @@
 			int alldone=numdone[0];
 			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
-			_printString_("\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/Krigingx.h
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/Krigingx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Krigingx/Krigingx.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _KRIGINGX_H
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../toolkits/toolkits.h"
 
Index: /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp	(revision 15396)
@@ -5,13 +5,12 @@
 #include "./Krigingx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
-#include "../../io/io.h"
+#include "../../classes/classes.h"
+#include "../../shared/io/io.h"
 
 /*FUNCTION pKrigingx{{{*/
 int pKrigingx(double** ppredictions,double **perror,double* obs_x, double* obs_y, double* obs_list, int obs_length,double* x_interp,double* y_interp,int n_interp,Options* options){
 
+#ifdef _HAVE_MPI_
 	int num_procs;
 	int my_rank;
@@ -28,4 +27,9 @@
 	Observations *observations = NULL;
 
+	/*timing*/
+	double   start, finish;
+	double   start_core, finish_core;
+	double   start_init, finish_init;
+
 	/*Get my_rank: */
 	my_rank=IssmComm::GetRank();
@@ -33,4 +37,5 @@
 
 	/*Get some Options*/
+	MPI_Barrier(MPI_COMM_WORLD); start=MPI_Wtime();
 	options->Get(&radius,"searchradius",0.);
 	options->Get(&mindata,"mindata",1);
@@ -38,5 +43,7 @@
 
 	/*Process observation dataset*/
+	MPI_Barrier(MPI_COMM_WORLD); start_init=MPI_Wtime();
 	observations=new Observations(obs_list,obs_x,obs_y,obs_length,options);
+	MPI_Barrier(MPI_COMM_WORLD); finish_init=MPI_Wtime();
 
 	/*Allocate output*/
@@ -47,4 +54,5 @@
 	options->Get(&output,"output",(char*)"prediction");
 
+	MPI_Barrier(MPI_COMM_WORLD); start_core=MPI_Wtime( );
 	if(strcmp(output,"quadtree")==0){
 		observations->QuadtreeColoring(predictions,x_interp,y_interp,n_interp);
@@ -60,8 +68,8 @@
 		/*partition loop across threads: */
 		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
-			_pprintLine_("      interpolation progress: "<<setw(6)<<setprecision(2)<<double(idx)/double(n_interp)*100<<"%");
+			_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);
 		}
-		_pprintLine_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%\n");
 
 #ifdef _HAVE_MPI_
@@ -74,12 +82,27 @@
 #endif
 	}
+	else if(strcmp(output,"v4")==0){
+
+		/*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");
+			observations->InterpolationV4(&predictions[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata);
+		}
+		_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());
+		xDelete<double>(predictions); predictions=sumpredictions;
+#endif
+	}
 	else if(strcmp(output,"nearestneighbor")==0){
 
 		/*partition loop across threads: */
 		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
-			_pprintLine_("      interpolation progress: "<<setw(6)<<setprecision(2)<<double(idx)/double(n_interp)*100<<"%");
+			_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);
 		}
-		_pprintLine_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%\n");
 
 #ifdef _HAVE_MPI_
@@ -95,8 +118,8 @@
 		/*partition loop across threads: */
 		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
-			_pprintLine_("      interpolation progress: "<<setw(6)<<setprecision(2)<<double(idx)/double(n_interp)*100<<"%");
+			_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);
 		}
-		_pprintLine_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%\n");
 
 #ifdef _HAVE_MPI_
@@ -109,4 +132,5 @@
 		_error_("output '" << output << "' not supported yet");
 	}
+	MPI_Barrier(MPI_COMM_WORLD); finish_core=MPI_Wtime( );
 
 	/*clean-up and Assign output pointer*/
@@ -116,5 +140,13 @@
 	*ppredictions = predictions;
 	*perror       = error;
+
+	MPI_Barrier(MPI_COMM_WORLD); finish=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");
+	_printf0_("\n   " << "Total elapsed time " << int((finish-start)/3600) << " hrs " << int(int(finish-start)%3600/60) << " min " << int(finish-start)%60 << " sec\n\n\n");
 	return 1;
+#else
+	_error_("MPI not available");
+#endif
 }/*}}}*/
 void ProcessVariogram(Variogram **pvariogram,Options* options){/*{{{*/
Index: /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 15396)
@@ -4,5 +4,5 @@
 
 #include "../VecMergex/VecMergex.h"
-#include "../../io/io.h"
+#include "../../shared/io/io.h"
 #include "./Mergesolutionfromftogx.h"
 
@@ -17,5 +17,5 @@
 
 	/*Display message*/
-	if(VerboseModule()) _pprintLine_("   Merging solution vector from fset to gset");
+	if(VerboseModule()) _printf0_("   Merging solution vector from fset to gset\n");
 
 	/*first, get gsize, fsize and ssize: */
Index: /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h
===================================================================
--- /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _MERGESOLUTIONFROMFTOGX_H
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h
===================================================================
--- /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _MESHPARTITIONX_H
 
-#include "../../include/include.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 15396)
@@ -7,5 +7,5 @@
 
 #include "../../shared/shared.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 15396)
@@ -3,12 +3,7 @@
  */ 
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
 #include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
-#include "../../Solverx/Solverx.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 15396)
@@ -1,10 +1,7 @@
-#include "../../../Container/Container.h"
-#include "../../../modules/modules.h"
-#include "../../../io/io.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
 #include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
 
 void	CreateConstraintsBalancethickness(Constraints** pconstraints, IoModel* iomodel){
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 15396)
@@ -2,11 +2,7 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 15396)
@@ -3,11 +3,7 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
 #include "../ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp	(revision 15396)
@@ -3,13 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../modules/modules.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 15396)
@@ -3,9 +3,6 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../io/io.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 15396)
@@ -2,11 +2,7 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../io/io.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 15396)
@@ -3,11 +3,7 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../io/io.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
 #include "../ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 15396)
@@ -3,13 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../modules/modules.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 15396)
@@ -3,11 +3,7 @@
  */ 
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 15396)
@@ -3,13 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../modules/modules.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 15396)
@@ -9,8 +9,6 @@
 #endif
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 #include "./ModelProcessorx.h"
 
@@ -56,9 +54,21 @@
 
 		#ifdef _HAVE_HYDROLOGY_
-		case HydrologyAnalysisEnum:
-			CreateNodesHydrology(pnodes, iomodel);
-			CreateConstraintsHydrology(pconstraints,iomodel);
-			CreateLoadsHydrology(ploads,iomodel);
-			UpdateElementsHydrology(elements,iomodel,analysis_counter,analysis_type);
+		case HydrologyShreveAnalysisEnum:
+			CreateNodesHydrologyShreve(pnodes, iomodel);
+			CreateConstraintsHydrologyShreve(pconstraints,iomodel);
+			CreateLoadsHydrologyShreve(ploads,iomodel);
+			UpdateElementsHydrologyShreve(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		case HydrologyDCInefficientAnalysisEnum:
+			CreateNodesHydrologyDCInefficient(pnodes, iomodel);
+			CreateConstraintsHydrologyDCInefficient(pconstraints,iomodel);
+			CreateLoadsHydrologyDCInefficient(ploads,iomodel);
+			UpdateElementsHydrologyDCInefficient(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		case HydrologyDCEfficientAnalysisEnum:
+			CreateNodesHydrologyDCEfficient(pnodes, iomodel);
+			CreateConstraintsHydrologyDCEfficient(pconstraints,iomodel);
+			CreateLoadsHydrologyDCEfficient(ploads,iomodel);
+			UpdateElementsHydrologyDCEfficient(elements,iomodel,analysis_counter,analysis_type);
 			break;
 		#endif
@@ -93,4 +103,13 @@
 			CreateLoadsBalancethickness(ploads,iomodel);
 			UpdateElementsBalancethickness(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		#endif
+
+		#ifdef _HAVE_GIA_
+		case GiaAnalysisEnum:
+			CreateNodesGia(pnodes, iomodel);
+			CreateConstraintsGia(pconstraints,iomodel);
+			CreateLoadsGia(ploads,iomodel);
+			UpdateElementsGia(elements,iomodel,analysis_counter,analysis_type);
 			break;
 		#endif
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 15396)
@@ -3,12 +3,8 @@
  */
 
-#include "../../Container/Container.h"
 #include "../../toolkits/toolkits.h"
-#include "../../io/io.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
 #include "../MeshPartitionx/MeshPartitionx.h"
-#include "../../include/include.h"
 #include "./ModelProcessorx.h"
 
@@ -21,4 +17,5 @@
 	int numberofvertices;
 	bool control_analysis;
+	bool dakota_analysis;
 
 	/*DataSets: */
@@ -32,4 +29,5 @@
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
 	iomodel->Constant(&materials_type,MaterialsEnum);
 
@@ -68,4 +66,10 @@
 			iomodel->FetchData(2,MaterialsRheologyBEnum,MaterialsRheologyNEnum);
 			for (i=0;i<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); 
+           #ifdef _HAVE_3D_
+				else       materials->InputDuplicate(MaterialsRheologyBEnum,QmuMaterialsRheologyBEnum); 
+           #endif
+			}
 			break;
 		case MatdamageiceEnum:
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 15396)
@@ -10,6 +10,6 @@
 
 #include "../../shared/shared.h"
-#include "../../io/io.h"
-#include "../../include/include.h"
+#include "../../classes/classes.h"
+#include "../../shared/io/io.h"
 #include "./ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 15396)
@@ -9,11 +9,8 @@
 #endif
 
-#include "../../Container/Container.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
 #include "../MeshPartitionx/MeshPartitionx.h"
-#include "../../io/io.h"
 #include "./ModelProcessorx.h"
 
@@ -24,18 +21,19 @@
 	Parameters *parameters       = NULL;
 	IssmDouble *requestedoutputs = NULL;
-	bool        isdelta18o;
+	IssmDouble  time;
+	bool        ispdd,isdelta18o;
 
 	/*parameters for mass flux: {{{*/
-	int      mass_flux_num_profiles=0;
-	bool     qmu_mass_flux_present=false;
-	bool     autodiff_mass_flux_present=false;
-	bool     mass_flux_present=false;
-	IssmDouble** array=NULL;
-	int*     mdims_array=NULL;
-	int*     ndims_array=NULL;
-	IssmDouble*  temp_matrix=NULL;
-	int      temp_m,temp_n;
-	IssmDouble*  matrix=NULL;
-	int      count;
+	int          mass_flux_num_profiles     = 0;
+	bool         qmu_mass_flux_present      = false;
+	bool         autodiff_mass_flux_present = false;
+	bool         mass_flux_present          = false;
+	IssmDouble **array                      = NULL;
+	int         *mdims_array                = NULL;
+	int         *ndims_array                = NULL;
+	IssmDouble  *temp_matrix                = NULL;
+	int          temp_m,temp_n;
+	IssmDouble  *matrix                     = NULL;
+	int          count;
 	/*}}}*/
 
@@ -76,5 +74,4 @@
 	parameters->AddObject(iomodel->CopyConstantObject(ConstantsReferencetemperatureEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(BalancethicknessStabilizationEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(HydrologyStabilizationEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(GroundinglineMeltingRateEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(ThermalMaxiterEnum));
@@ -89,4 +86,5 @@
 	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofelementsEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofverticesEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberoflayersEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsIoGatherEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsResultsAsPatchesEnum));
@@ -96,4 +94,5 @@
 	parameters->AddObject(iomodel->CopyConstantObject(TransientIsthermalEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(TransientIsgroundinglineEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsgiaEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsenthalpyEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MaterialsRheologyLawEnum));
@@ -105,22 +104,30 @@
 	parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsIsdelta18oEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsIssmbgradientsEnum));
-
-	iomodel->Constant(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
-	if(isdelta18o){
-		IssmDouble *temp = NULL;
-		IssmDouble  yts;
-		int         N,M;
-
-		iomodel->Constant(&yts,ConstantsYtsEnum);
-
-		iomodel->FetchData(&temp,&N,&M,SurfaceforcingsDelta18oEnum); _assert_(N==2);
-		for(i=0;i<M;i++) temp[M+i]=yts*temp[M+i];
-		parameters->AddObject(new TransientParam(SurfaceforcingsDelta18oEnum,&temp[0],&temp[M],M));
-		iomodel->DeleteData(temp,SurfaceforcingsDelta18oEnum);
-
-		iomodel->FetchData(&temp,&N,&M,SurfaceforcingsDelta18oSurfaceEnum); _assert_(N==2);
-		for(i=0;i<M;i++) temp[M+i]=yts*temp[M+i];
-		parameters->AddObject(new TransientParam(SurfaceforcingsDelta18oSurfaceEnum,&temp[0],&temp[M],M));
-		iomodel->DeleteData(temp,SurfaceforcingsDelta18oSurfaceEnum);
+	parameters->AddObject(iomodel->CopyConstantObject(GiaCrossSectionShapeEnum));
+
+	iomodel->Constant(&ispdd,SurfaceforcingsIspddEnum);
+	if(ispdd){
+
+		parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsDesfacEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsS0pEnum));
+
+		iomodel->Constant(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+		if(isdelta18o){
+			IssmDouble *temp = NULL;
+			IssmDouble  yts;
+			int         N,M;
+
+			iomodel->Constant(&yts,ConstantsYtsEnum);
+
+			iomodel->FetchData(&temp,&N,&M,SurfaceforcingsDelta18oEnum); _assert_(N==2);
+			for(i=0;i<M;i++) temp[M+i]=yts*temp[M+i];
+			parameters->AddObject(new TransientParam(SurfaceforcingsDelta18oEnum,&temp[0],&temp[M],M));
+			iomodel->DeleteData(temp,SurfaceforcingsDelta18oEnum);
+
+			iomodel->FetchData(&temp,&N,&M,SurfaceforcingsDelta18oSurfaceEnum); _assert_(N==2);
+			for(i=0;i<M;i++) temp[M+i]=yts*temp[M+i];
+			parameters->AddObject(new TransientParam(SurfaceforcingsDelta18oSurfaceEnum,&temp[0],&temp[M],M));
+			iomodel->DeleteData(temp,SurfaceforcingsDelta18oSurfaceEnum);
+		}
 	}
 
@@ -129,5 +136,7 @@
 	parameters->AddObject(new IntParam(AnalysisTypeEnum,analysis_type));
 	parameters->AddObject(new IntParam(AnalysisCounterEnum,analysis_counter));
-	parameters->AddObject(new DoubleParam(TimeEnum,0.0));  //start at time 0 by default for all solutions FIXME: to be deleted
+
+	iomodel->Constant(&time,TimesteppingStartTimeEnum);
+	parameters->AddObject(new DoubleParam(TimeEnum,time));  //start at time 0 by default for all solutions FIXME: to be deleted
 	parameters->AddObject(new IntParam(StepEnum,1));  //start at time 0 by default for all solutions FIXME: to be deleted
 
@@ -217,4 +226,11 @@
 	/*}}}*/
 
+	/*Solution specific parameters (FIXME: extend to other params)*/
+	#ifdef _HAVE_HYDROLOGY_
+	CreateParametersHydrologyShreve(&parameters,iomodel,solution_type,analysis_type);
+	CreateParametersHydrologyDCInefficient(&parameters,iomodel,solution_type,analysis_type);
+	CreateParametersHydrologyDCEfficient(&parameters,iomodel,solution_type,analysis_type);
+	#endif
+
 	/*Before returning, create parameters in case we are running Qmu or control types runs: */
 	#ifdef _HAVE_CONTROL_
@@ -230,7 +246,4 @@
 	#endif
 
-	/*Go through all parameters, and convert units to SI: */
-	parameters->UnitConversion(ExtToIuEnum);
-
 	/*Assign output pointer: */
 	*pparameters=parameters;
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 15396)
@@ -10,6 +10,6 @@
 
 #include "../../shared/shared.h"
-#include "../../io/io.h"
-#include "../../include/include.h"
+#include "../../shared/io/io.h"
+#include "../../classes/classes.h"
 #include "./ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 15396)
@@ -3,11 +3,7 @@
  */ 
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../io/io.h"
-#include "../../../include/include.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
 #include "../ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 15396)
@@ -3,9 +3,6 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
@@ -91,6 +88,4 @@
 		timesx[j]=spcvx[(Mx-1)*Nx+j];
 	}
-	/*unit conversion: */
-	UnitConversion(timesx,Nx,ExtToIuEnum,TimeEnum);
 	/*figure out times: */
 	timesy=xNew<IssmDouble>(Ny);
@@ -98,6 +93,4 @@
 		timesy[j]=spcvy[(My-1)*Ny+j];
 	}
-	/*unit conversion: */
-	UnitConversion(timesy,Ny,ExtToIuEnum,TimeEnum);
 	/*figure out times: */
 	timesz=xNew<IssmDouble>(Nz);
@@ -105,6 +98,4 @@
 		timesz[j]=spcvz[(Mz-1)*Nz+j];
 	}
-	/*unit conversion: */
-	UnitConversion(timesz,Nz,ExtToIuEnum,TimeEnum);
 
 	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 15396)
@@ -2,11 +2,7 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
@@ -154,4 +150,5 @@
 
 	/*Create Riffront loads for rifts: */
+	#ifdef _HAVE_RIFTS_
 	if(numrifts){
 		iomodel->FetchData(&riftinfo,&numriftsegments,NULL,RiftsRiftstructEnum);
@@ -166,4 +163,5 @@
 		xDelete<IssmDouble>(riftinfo);
 	}
+	#endif
 
 	/*Assign output pointer: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 15396)
@@ -3,12 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
@@ -55,4 +51,31 @@
 	}
 
+	if(false){
+		/*Quadratic element*/
+		int numberofedges;
+		int  element1,element2;
+		bool my_edge;
+
+		iomodel->Constant(&numberofedges,MeshNumberofedgesEnum);
+
+		for (i=0;i<numberofedges;i++){
+
+			/*Get left and right elements*/
+			element1=reCast<int>(iomodel->Data(MeshEdgesEnum)[4*i+2])-1; //edges are [node1 node2 elem1 elem2]
+			element2=reCast<int>(iomodel->Data(MeshEdgesEnum)[4*i+3])-1; //edges are [node1 node2 elem1 elem2]
+
+			/*Check whether we should include this edge (element2 is -2 for boundary edges)*/
+			my_edge = iomodel->my_elements[element1];
+			if(!my_edge && element2>=0){
+				my_edge = iomodel->my_elements[element2];
+			}
+
+			/*Add node on edge*/
+			if(my_edge){
+				nodes->AddObject(new Node(iomodel->nodecounter+numberofvertices+i+1,numberofvertices+i,numberofvertices+i+1,i,iomodel,DiagnosticHorizAnalysisEnum));
+			}
+		}
+	}
+
 	/*Clean fetched data: */
 	iomodel->DeleteData(9,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBordermacayealEnum,FlowequationBorderstokesEnum,
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 15396)
@@ -8,13 +8,8 @@
 #endif
 
-#include "../../../Container/Container.h"
-#include "../../../modules/modules.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
@@ -69,4 +64,6 @@
 	iomodel->FetchDataToInput(elements,VxEnum);
 	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,LoadingforceXEnum);
+	iomodel->FetchDataToInput(elements,LoadingforceYEnum);
 	if(materials_type==MatdamageiceEnum){
 		iomodel->FetchDataToInput(elements,MaterialsRheologyZEnum);
@@ -79,4 +76,5 @@
 		iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
 		iomodel->FetchDataToInput(elements,FlowequationBorderstokesEnum);
+		iomodel->FetchDataToInput(elements,LoadingforceZEnum);
 	}
 
@@ -90,5 +88,5 @@
 	elements->InputDuplicate(VxEnum,InversionVxObsEnum);
 	if(dakota_analysis)elements->InputDuplicate(VxEnum,QmuVxEnum);
-	
+
 	#ifdef _HAVE_ANDROID_
 	elements->InputDuplicate(FrictionCoefficientEnum,AndroidFrictionCoefficientEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 15396)
@@ -3,9 +3,6 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp	(revision 15396)
@@ -2,11 +2,7 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp	(revision 15396)
@@ -3,12 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp	(revision 15396)
@@ -3,13 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../modules/modules.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 15396)
@@ -3,9 +3,6 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp	(revision 15396)
@@ -2,11 +2,7 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp	(revision 15396)
@@ -3,12 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp	(revision 15396)
@@ -3,13 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../modules/modules.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 15396)
@@ -4,6 +4,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../classes/classes.h"
 
 void DistributeNumDofs(DofIndexing* index,int analysis_type,IssmDouble* vertices_type){
@@ -80,5 +79,11 @@
 		numdofs=1;
 	}
-	else if (analysis_type==HydrologyAnalysisEnum){
+	else if (analysis_type==HydrologyDCInefficientAnalysisEnum){
+		numdofs=1;
+	}
+	else if (analysis_type==HydrologyDCEfficientAnalysisEnum){
+		numdofs=1;
+	}
+	else if (analysis_type==HydrologyShreveAnalysisEnum){
 		numdofs=1;
 	}
@@ -87,4 +92,7 @@
 	}
 	else if (analysis_type==PrognosticAnalysisEnum){
+		numdofs=1;
+	}
+	else if (analysis_type==GiaAnalysisEnum){
 		numdofs=1;
 	}
Index: /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 15396)
@@ -10,9 +10,6 @@
 
 #include <string.h>
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../io/io.h"
-#include "../../include/include.h"
 #include "../MeshPartitionx/MeshPartitionx.h"
 #include "../ModelProcessorx/ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 15396)
@@ -3,11 +3,7 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../io/io.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
@@ -79,6 +75,4 @@
 			times[j]=spcvector[(M-1)*N+j];
 		}
-		/*unit conversion: */
-		UnitConversion(times,N,ExtToIuEnum,TimeEnum);
 
 		/*Create constraints from x,y,z: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 15396)
@@ -2,11 +2,7 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 15396)
@@ -3,10 +3,6 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
-#include "../../../include/include.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 15396)
@@ -3,13 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../modules/modules.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Gia/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Gia/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Gia/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,8 @@
+# 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 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateConstraintsGia.cpp	(revision 15396)
@@ -0,0 +1,20 @@
+/*
+ * CreateConstraintsGia.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsGia(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;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateLoadsGia.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateLoadsGia.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateLoadsGia.cpp	(revision 15396)
@@ -0,0 +1,19 @@
+/*! \file CreateLoadsGia.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsGia(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;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateNodesGia.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateNodesGia.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateNodesGia.cpp	(revision 15396)
@@ -0,0 +1,48 @@
+/*
+ * CreateNodesGia.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+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;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Gia/UpdateElementsGia.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Gia/UpdateElementsGia.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Gia/UpdateElementsGia.cpp	(revision 15396)
@@ -0,0 +1,40 @@
+/*
+ * UpdateElementsGia:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+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++){
+		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.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,GiaMantleViscosityEnum);
+	iomodel->FetchDataToInput(elements,GiaLithosphereThicknessEnum);
+
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,8 @@
+# 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 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateConstraintsHydrologyDCEfficient.cpp	(revision 15396)
@@ -0,0 +1,39 @@
+/*
+ * CreateConstraintsHydrologyDCEfficient.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
+
+void	CreateConstraintsHydrologyDCEfficient(Constraints** pconstraints, IoModel* iomodel){
+
+	/*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?*/
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum){
+		*pconstraints=constraints;
+		return;
+	}
+
+	/*Do we want an efficient layer*/
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer){
+		*pconstraints=constraints;
+		return;
+	}
+
+	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpceplHeadEnum,HydrologyDCEfficientAnalysisEnum);
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp	(revision 15396)
@@ -0,0 +1,44 @@
+/*! \file CreateLoadsHydrologyDCEfficient.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+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?*/
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum){
+		*ploads=loads;
+		return;
+	}
+
+	/*Do we want an efficient layer*/
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer){
+		*ploads=loads;
+		return;
+	}
+
+	/*Nothing for now*/
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateNodesHydrologyDCEfficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateNodesHydrologyDCEfficient.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateNodesHydrologyDCEfficient.cpp	(revision 15396)
@@ -0,0 +1,60 @@
+/*
+ * CreateNodesHydrologyDCEfficient.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesHydrologyDCEfficient(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int  i;
+	bool isefficientlayer;
+	bool continuous_galerkin=true;
+	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;
+	}
+
+	/*Do we want an efficient layer*/
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer){
+		*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,HydrologyDCEfficientAnalysisEnum));
+
+		}
+	}
+	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateParametersHydrologyDCEfficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateParametersHydrologyDCEfficient.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateParametersHydrologyDCEfficient.cpp	(revision 15396)
@@ -0,0 +1,39 @@
+/*!\file: CreateParametersHydrologyDCEfficient.cpp
+ * \brief driver for creating parameters dataset, for control analysis.
+ */ 
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void CreateParametersHydrologyDCEfficient(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
+
+	Parameters *parameters = NULL;
+	int         hydrology_model;
+	bool        isefficientlayer;
+
+	/*Get parameters: */
+	parameters=*pparameters;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum){
+		*pparameters=parameters;
+		return;
+	}
+
+	/*Do we want an efficient layer*/
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer){
+		*pparameters=parameters;
+		return;
+	}
+
+	/*Nothing for now*/
+
+	/*Assign output pointer: */
+	*pparameters=parameters;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/UpdateElementsHydrologyDCEfficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/UpdateElementsHydrologyDCEfficient.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/UpdateElementsHydrologyDCEfficient.cpp	(revision 15396)
@@ -0,0 +1,53 @@
+/*
+ * UpdateElementsHydrologyDCEfficient:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsHydrologyDCEfficient(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	bool   isefficientlayer;
+	int    hydrology_model;
+	int    numberofelements;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+
+	/*Now, do we really want DC?*/
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	/*Fetch data needed: */
+	iomodel->FetchData(1,MeshElementsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<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.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	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,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,EplHeadEnum);
+
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,8 @@
+# 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 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateConstraintsHydrologyDCInefficient.cpp	(revision 15396)
@@ -0,0 +1,32 @@
+/*
+ * CreateConstraintsHydrologyDCInefficient.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
+
+void	CreateConstraintsHydrologyDCInefficient(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Recover pointer: */
+	int          hydrology_model;
+	Constraints* constraints=*pconstraints;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*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);
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateLoadsHydrologyDCInefficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateLoadsHydrologyDCInefficient.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateLoadsHydrologyDCInefficient.cpp	(revision 15396)
@@ -0,0 +1,45 @@
+/*! \file CreateLoadsHydrologyDCInefficient.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsHydrologyDCInefficient(Loads** ploads, IoModel* iomodel){
+
+	/*Intermediary*/
+	int      hydrology_model;
+	int      numberofvertices;
+	Pengrid *pengrid = NULL;
+
+	/*Recover pointer: */
+	Loads* loads=*ploads;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+
+	if(hydrology_model!=HydrologydcEnum){
+		*ploads=loads;
+		return;
+	}
+
+	//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));
+		}
+	}
+	iomodel->DeleteData(1,MeshElementsEnum);
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateNodesHydrologyDCInefficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateNodesHydrologyDCInefficient.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateNodesHydrologyDCInefficient.cpp	(revision 15396)
@@ -0,0 +1,52 @@
+/*
+ * CreateNodesHydrologyDCInefficient.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesHydrologyDCInefficient(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int  i;
+	bool continuous_galerkin=true;
+	int  hydrology_model;
+	int  numberofvertices;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Recover pointer: */
+	Nodes* nodes=*pnodes;
+
+	/*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;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateParametersHydrologyDCInefficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateParametersHydrologyDCInefficient.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateParametersHydrologyDCInefficient.cpp	(revision 15396)
@@ -0,0 +1,59 @@
+/*!\file: CreateParametersHydrologyDCInefficient.cpp
+ * \brief driver for creating parameters dataset, for control analysis.
+ */ 
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void CreateParametersHydrologyDCInefficient(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
+
+	Parameters *parameters = NULL;
+	int         hydrology_model;
+	int         sedimentlimit_flag;
+	int         transfer_flag;
+	bool        isefficientlayer;
+	IssmDouble  sedimentlimit;
+	IssmDouble  penalty_factor;
+	IssmDouble  leakagefactor;
+	IssmDouble  rel_tol;
+
+	/*Get parameters: */
+	parameters=*pparameters;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum){
+		*pparameters=parameters;
+		return;
+	}
+
+	iomodel->FetchData(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	iomodel->FetchData(&sedimentlimit_flag,HydrologydcSedimentlimitFlagEnum);
+	iomodel->FetchData(&transfer_flag,HydrologydcTransferFlagEnum);
+	iomodel->FetchData(&penalty_factor,HydrologydcPenaltyFactorEnum);
+	iomodel->FetchData(&rel_tol,HydrologydcRelTolEnum);
+
+	if(sedimentlimit_flag==1){
+		iomodel->FetchData(&sedimentlimit,HydrologydcSedimentlimitEnum);
+		parameters->AddObject(new DoubleParam(HydrologydcSedimentlimitEnum,sedimentlimit));
+	}
+
+	if(transfer_flag==1){
+		iomodel->FetchData(&leakagefactor,HydrologydcLeakageFactorEnum);
+		parameters->AddObject(new DoubleParam(HydrologydcLeakageFactorEnum,leakagefactor));
+	}
+
+	parameters->AddObject(new DoubleParam(HydrologydcPenaltyFactorEnum,penalty_factor));
+	parameters->AddObject(new IntParam(HydrologyModelEnum,hydrology_model));
+	parameters->AddObject(new BoolParam(HydrologydcIsefficientlayerEnum,isefficientlayer));
+	parameters->AddObject(new IntParam(HydrologydcSedimentlimitFlagEnum,sedimentlimit_flag));
+	parameters->AddObject(new IntParam(HydrologydcTransferFlagEnum,transfer_flag));
+	parameters->AddObject(new DoubleParam(HydrologydcRelTolEnum,rel_tol));
+
+	/*Assign output pointer: */
+	*pparameters=parameters;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/UpdateElementsHydrologyDCInefficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/UpdateElementsHydrologyDCInefficient.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/UpdateElementsHydrologyDCInefficient.cpp	(revision 15396)
@@ -0,0 +1,51 @@
+/*
+ * UpdateElementsHydrologyDCInefficient:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsHydrologyDCInefficient(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	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?*/
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	iomodel->FetchData(1,MeshElementsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<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.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	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,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SedimentHeadEnum);
+	if(isefficientlayer)iomodel->FetchDataToInput(elements,HydrologydcMaskEplactiveEnum);
+
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,8 @@
+# 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 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateConstraintsHydrologyShreve.cpp	(revision 15396)
@@ -0,0 +1,33 @@
+/*
+ * CreateConstraintsHydrologyShreve.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
+
+void	CreateConstraintsHydrologyShreve(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Recover pointer: */
+	int          hydrology_model;
+	bool         isefficientlayer;
+	Constraints* constraints=*pconstraints;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+
+	if(hydrology_model!=HydrologyshreveEnum){
+		*pconstraints=constraints;
+		return;
+	}
+
+	IoModelToConstraintsx(constraints,iomodel,HydrologyshreveSpcwatercolumnEnum,HydrologyShreveAnalysisEnum);
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateLoadsHydrologyShreve.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateLoadsHydrologyShreve.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateLoadsHydrologyShreve.cpp	(revision 15396)
@@ -0,0 +1,23 @@
+/*! \file CreateLoadsHydrologyShreve.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsHydrologyShreve(Loads** ploads, IoModel* iomodel){
+
+	/*Intermediary*/
+	int      numberofvertices;
+	Pengrid *pengrid = NULL;
+
+	/*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 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateNodesHydrologyShreve.cpp	(revision 15396)
@@ -0,0 +1,51 @@
+/*
+ * CreateNodesHydrologyShreve.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesHydrologyShreve(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int  i;
+	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;
+
+	/*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;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateParametersHydrologyShreve.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateParametersHydrologyShreve.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateParametersHydrologyShreve.cpp	(revision 15396)
@@ -0,0 +1,33 @@
+/*!\file: CreateParametersHydrologyShreve.cpp
+ * \brief driver for creating parameters dataset, for control analysis.
+ */ 
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void CreateParametersHydrologyShreve(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
+
+	Parameters *parameters = NULL;
+	int         hydrology_model;
+	bool        isefficientlayer;
+
+	/*Get parameters: */
+	parameters=*pparameters;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want Shreve?*/
+	if(hydrology_model!=HydrologyshreveEnum){
+		*pparameters=parameters;
+		return;
+	}
+
+	parameters->AddObject(new IntParam(HydrologyModelEnum,hydrology_model));
+	parameters->AddObject(iomodel->CopyConstantObject(HydrologyshreveStabilizationEnum));
+
+	/*Assign output pointer: */
+	*pparameters=parameters;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/UpdateElementsHydrologyShreve.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/UpdateElementsHydrologyShreve.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/UpdateElementsHydrologyShreve.cpp	(revision 15396)
@@ -0,0 +1,50 @@
+/*
+ * UpdateElementsHydrologyShreve:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsHydrologyShreve(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	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++){
+		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.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	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,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,WatercolumnEnum);
+
+	elements->InputDuplicate(WatercolumnEnum,WaterColumnOldEnum);
+
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 15396)
@@ -3,9 +3,6 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../io/io.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 15396)
@@ -2,11 +2,7 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 15396)
@@ -3,10 +3,6 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../include/include.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 15396)
@@ -3,13 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../modules/modules.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 15396)
@@ -9,11 +9,7 @@
 #endif
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
-#include "../../io/io.h"
-#include "../../Container/Container.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../include/include.h"
-#include "../../modules/modules.h"
+#include "./ModelProcessorx.h"
 
 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){
@@ -45,9 +41,11 @@
 	SetVerbosityLevel(verbose);
 
+	if(VerboseMProcessor()) _printf0_("   starting model processor \n");
+
 	for(i=0;i<nummodels;i++){
 
 		analysis_type=analysis_type_list[i];
 
-		/*Hack for trasient runs (to be improved)*/
+		/*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;
@@ -67,7 +65,8 @@
 		if(solution_type==SteadystateSolutionEnum && analysis_type==EnthalpyAnalysisEnum && isenthalpy==false) continue;
 
-		if(VerboseMProcessor()) _pprintLine_("   creating datasets for analysis " << EnumToStringx(analysis_type));
+		if(VerboseMProcessor()) _printf0_("   creating datasets for analysis " << EnumToStringx(analysis_type) << "\n");
 		CreateDataSets(&elements,&nodes,&vertices,&materials,&constraints,&loads,&parameters,iomodel,rootpath,solution_type,analysis_type,nummodels,i);
 	}
+	if(VerboseMProcessor()) _printf0_("   done with model processor \n");
 
 	/*Free resources:*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 15396)
@@ -8,10 +8,5 @@
 #define RIFTINFOSIZE 12
 
-class DataSet;
-class IoModel;
-class Parameters;
-class DofIndexing;
-
-#include "../../io/io.h"
+#include "../../classes/classes.h"
 
 void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* iomodel_handle,char* rootpath,const int solution_type,const int nummodels,const int* analysis_type_listh);
@@ -21,7 +16,10 @@
 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  CreateParametersAutodiff(Parameters** pparameters,IoModel* iomodel,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);
 
@@ -45,4 +43,12 @@
 void  CreateLoadsDiagnosticHutter(Loads** ploads, IoModel* iomodel);
 void	UpdateElementsDiagnosticHutter(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);
+#endif
 
 /*bed slope*/
@@ -70,9 +76,19 @@
 void	UpdateElementsEnthalpy(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
-/*hydrology:*/
-void	CreateNodesHydrology(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsHydrology(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsHydrology(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsHydrology(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);
+
+/*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);
 
 /*melting:*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 15396)
@@ -10,9 +10,6 @@
 
 #include <string.h>
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../io/io.h"
-#include "../../include/include.h"
 #include "../MeshPartitionx/MeshPartitionx.h"
 #include "../ModelProcessorx/ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp	(revision 15396)
@@ -1,10 +1,7 @@
-#include "../../../Container/Container.h"
-#include "../../../modules/modules.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../io/io.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
 
 void	CreateConstraintsPrognostic(Constraints** pconstraints, IoModel* iomodel){
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp	(revision 15396)
@@ -2,11 +2,7 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 15396)
@@ -3,12 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../io/io.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 15396)
@@ -3,13 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../modules/modules.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
@@ -63,4 +58,7 @@
 		elements->InputDuplicate(ThicknessEnum,QmuThicknessEnum);
 		elements->InputDuplicate(SurfaceEnum,QmuSurfaceEnum);
+		elements->InputDuplicate(BasalforcingsMeltingRateEnum,QmuMeltingEnum);
+		elements->InputDuplicate(VxEnum,QmuVxEnum);
+		elements->InputDuplicate(VyEnum,QmuVyEnum);
 	}
 
@@ -70,4 +68,10 @@
 		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){
Index: /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 15396)
@@ -9,8 +9,6 @@
 #endif
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 #include "./ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 15396)
@@ -3,9 +3,6 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../io/io.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 15396)
@@ -2,11 +2,7 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../io/io.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 15396)
@@ -3,11 +3,7 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../io/io.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
 #include "../ModelProcessorx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 15396)
@@ -3,13 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../modules/modules.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 15396)
@@ -3,12 +3,9 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../modules/modules.h"
-#include "../../../io/io.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
 
 void	CreateConstraintsThermal(Constraints** pconstraints, IoModel* iomodel){
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 15396)
@@ -2,11 +2,7 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
@@ -14,8 +10,7 @@
 
 	/*Intermediary*/
-	int i;
-	int    dim;
-	int    numberofvertices;
-	Pengrid*    pengrid  = NULL;
+	int      dim;
+	int      numberofvertices;
+	Pengrid *pengrid          = NULL;
 
 	/*Recover pointer: */
@@ -36,5 +31,5 @@
 	CreateSingleNodeToElementConnectivity(iomodel);
 
-	for (i=0;i<numberofvertices;i++){
+	for(int i=0;i<numberofvertices;i++){
 
 		/*keep only this partition's nodes:*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 15396)
@@ -3,10 +3,6 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
-#include "../../../include/include.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 15396)
@@ -3,13 +3,8 @@
  */
 
-#include "../../../Container/Container.h"
-#include "../../../modules/modules.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
@@ -63,6 +58,8 @@
 	if(dakota_analysis){
 		elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
+		elements->InputDuplicate(PressureEnum,QmuPressureEnum);
 		elements->InputDuplicate(BasalforcingsMeltingRateEnum,QmuMeltingEnum);
 	}
+
 	/*Free data: */
 	iomodel->DeleteData(1,MeshElementsEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 15396)
@@ -3,15 +3,47 @@
  */
 
-#include "../../../Container/Container.h"
 #include "../../../toolkits/toolkits.h"
-#include "../../../io/io.h"
-#include "../../../modules/modules.h"
-#include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
-#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
 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 15395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 15396)
@@ -9,8 +9,6 @@
 #endif
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 #include "./ModelProcessorx.h"
 
Index: /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 15396)
@@ -6,9 +6,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
-void NodalValuex( IssmDouble* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units){
+void NodalValuex( IssmDouble* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
 
 	int my_rank;
@@ -31,5 +29,5 @@
 	for(i=0;i<elements->Size();i++){
 		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		found=element->NodalValue(&value,index,natureofdataenum,process_units);
+		found=element->NodalValue(&value,index,natureofdataenum);
 		if (found){
 			cpu_found=my_rank;
Index: /issm/trunk/src/c/modules/NodalValuex/NodalValuex.h
===================================================================
--- /issm/trunk/src/c/modules/NodalValuex/NodalValuex.h	(revision 15395)
+++ /issm/trunk/src/c/modules/NodalValuex/NodalValuex.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _NODALVALUEX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void NodalValuex( IssmDouble* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void NodalValuex( IssmDouble* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif  /* _NODALVALUEX_H */
Index: /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 15396)
@@ -14,7 +14,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void	NodeConnectivityx(int** pconnectivity,int* pwidth,int* elements, int nels, int nods){
Index: /issm/trunk/src/c/modules/NodesDofx/NodesDofx.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodesDofx/NodesDofx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/NodesDofx/NodesDofx.cpp	(revision 15396)
@@ -6,7 +6,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void NodesDofx(Nodes* nodes, Parameters* parameters,int configuration_type){
Index: /issm/trunk/src/c/modules/NodesDofx/NodesDofx.h
===================================================================
--- /issm/trunk/src/c/modules/NodesDofx/NodesDofx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/NodesDofx/NodesDofx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _NODESDOFX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Orthx/Orthx.h
===================================================================
--- /issm/trunk/src/c/modules/Orthx/Orthx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Orthx/Orthx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _ORTHX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../include/include.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
 
Index: /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 15396)
@@ -12,7 +12,6 @@
 #include <stdio.h>
 #include "./OutputResultsx.h"
-#include "../../Container/Container.h"
-#include "../../io/io.h"
-#include "../../classes/objects/objects.h"
+#include "../../shared/io/io.h"
+#include "../../classes/classes.h"
 
 void OutputResultsx(Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Results* results){
@@ -39,5 +38,4 @@
 
 	/*We have results inside our elements, loads, etc ... Get them out of there, into the results dataset: */
-	elements->ProcessResultsUnits();
 	elements->ToResults(results,parameters);
 	elements->DeleteResults();
Index: /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.h
===================================================================
--- /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.h	(revision 15396)
@@ -12,5 +12,5 @@
 #endif
 
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 void OutputResultsx(Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads,  Materials* materials, Parameters* parameters, Results* results);
Index: /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.cpp	(revision 15396)
@@ -7,7 +7,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void OutputRiftsx( Vec* priftproperties, Loads* loads, int numrifts){
Index: /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.h
===================================================================
--- /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _OUTPUTRIFTSX_H
 
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ParseToolkitsOptionsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ParseToolkitsOptionsx/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/modules/ParseToolkitsOptionsx/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,8 @@
+# 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 15396)
+++ /issm/trunk/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp	(revision 15396)
@@ -0,0 +1,128 @@
+/*!\file ParseToolkitsOptionsx
+ * * \brief: parse options present in a petsc file, and create petsc options 
+ * objects accordingly. This will be used to drive the behaviour of Toolkits for 
+ * each analysis type.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+
+#include "./ParseToolkitsOptionsx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void ParseToolkitsOptionsx(Parameters* parameters,FILE* fid){
+
+	char line [1000];
+	int my_rank;
+	int i;
+
+	/*intermediary: */
+	IssmDouble* analyses=NULL;
+	char** strings=NULL;
+	int numanalyses;
+	char* string=NULL;
+	char* newstring=NULL;
+	char* catstring=NULL;
+	int   stringlength;
+
+	/*Get my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(my_rank==0){
+
+		/*Now, go through lines and figure out how many analyses we have: */
+		numanalyses=0;
+		while ( fgets(line, sizeof line, fid) ){
+			/*skip comments and empty lines: */
+			if ((line[0]=='%') || (line[0]=='\n') || (line[0]==' ') || (line[0]=='\t') || (line[0]=='\r'))continue;
+			/*ok, first time, we should get an analysis enum, starting with a +: */
+			if (line[0]=='+')numanalyses++;
+			else continue;
+		}
+
+		/*Now, allocate analyses and strings: */
+		analyses=xNew<IssmDouble>(numanalyses);
+		strings=xNew<char*>(numanalyses);
+		for(i=0;i<numanalyses;i++)strings[i]=NULL; 
+
+		/*Go back to beginning of file:*/
+		fseek(fid,0,SEEK_SET);
+		numanalyses=0;
+		while ( fgets(line, sizeof line, fid) ){
+
+			/*skip comments and empty lines: */
+			if ((line[0]=='%') || (line[0]=='\n') || (line[0]==' ') || (line[0]=='\t') || (line[0]=='\r'))continue;
+
+			/*Get rid of end of line: */
+			line[strlen(line)-1]='\0';
+
+			if (line[0]=='+'){ /*this is the analysis line: */
+				analyses[numanalyses]=StringToEnumx(&line[1]);  //skip the '+'
+				numanalyses++;
+			}
+			else{ /*this is an option corresponding to analysis numanalyses-1. Add it 
+			to the already existing options*/
+				if(strings[numanalyses-1]==NULL){
+					string=xNew<char>((strlen(line)+1)); 
+					xMemCpy<char>(string,line,(strlen(line)+1));
+
+					strings[numanalyses-1]=string;
+				}
+				else{
+					string=strings[numanalyses-1];
+					newstring=xNew<char>((strlen(line)+1));
+					xMemCpy<char>(newstring,line,(strlen(line)+1));
+
+					/*concatenate:*/
+					catstring=xNew<char>(strlen(string)+1+strlen(newstring)+1+1); //fit in a space " "
+					xMemCpy<char>(catstring,string,(strlen(string)+1));
+
+					strcat(catstring," ");
+					strcat(catstring,newstring);
+					strings[numanalyses-1]=catstring;
+					xDelete<char>(newstring);
+					xDelete<char>(string);
+				}
+			}
+		}
+	}
+
+	/*Ok, broadcast to other cpus: */
+ 	#ifdef _HAVE_MPI_
+	MPI_Bcast(&numanalyses,1,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
+	for(i=0;i<numanalyses;i++){
+		char* string=strings[i];
+		if(my_rank==0){
+			if(string==NULL) _error_("PETSc options for analysis " << EnumToStringx(reCast<int>(analyses[i])) << " have been declared but were not found");
+		}
+		if(my_rank==0)stringlength=(strlen(string)+1)*sizeof(char);
+		#ifdef _HAVE_MPI_
+		MPI_Bcast(&stringlength,1,MPI_INT,0,IssmComm::GetComm());
+		if(my_rank!=0)string=xNew<char>(stringlength);
+		MPI_Bcast(string,stringlength,MPI_CHAR,0,IssmComm::GetComm());
+		if(my_rank!=0)strings[i]=string;
+		#endif
+	}
+
+	/*Ok, out of strings and analyses and numanalyses, create parameters, and plug them into parameters container: */
+	parameters->AddObject(new StringArrayParam(ToolkitsOptionsStringsEnum,strings,numanalyses));
+	parameters->AddObject(new DoubleVecParam(ToolkitsOptionsAnalysesEnum,analyses,numanalyses));
+
+	/*Clean up and return*/
+	for(i=0;i<numanalyses;i++) xDelete<char>(strings[i]);
+	xDelete<char*>(strings);
+	xDelete<IssmDouble>(analyses);
+	return;
+}
Index: /issm/trunk/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h
===================================================================
--- /issm/trunk/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h	(revision 15396)
+++ /issm/trunk/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h	(revision 15396)
@@ -0,0 +1,13 @@
+/*!\file:  ParseToolkitsOptionsx.h
+ * \brief header file for parsing petsc options file
+ */ 
+
+#ifndef _PARSEPETSCOPTIONSX_H
+#define _PARSEPETSCOPTIONSX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void ParseToolkitsOptionsx(Parameters* parameters, FILE* petscoptionsfid);
+
+#endif  /* _PARSEPETSCOPTIONSX_H */
Index: /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp	(revision 15396)
@@ -4,9 +4,9 @@
 #include "./PointCloudFindNeighborsx.h"
 
-int PointCloudFindNeighborsx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, double mindistance,double multithread){
+int PointCloudFindNeighborsx(IssmSeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, double mindistance,double multithread){
 
 	/*output: */
-	SeqVec<IssmPDouble>* flags=NULL;
-	flags=new SeqVec<IssmPDouble>(nods);
+	IssmSeqVec<IssmPDouble>* flags=NULL;
+	flags=new IssmSeqVec<IssmPDouble>(nods);
 
 	/*threading: */
Index: /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 15396)
@@ -7,8 +7,8 @@
 
 #include "../../shared/shared.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-int PointCloudFindNeighborsx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, double mindistance,double multithread);
+int PointCloudFindNeighborsx(IssmSeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, double mindistance,double multithread);
 
 /*threading: */
@@ -19,5 +19,5 @@
 	int nods;
 	double mindistance;
-	SeqVec<IssmPDouble>* flags;
+	IssmSeqVec<IssmPDouble>* flags;
 
 } PointCloudFindNeighborsThreadStruct;
Index: /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 15396)
@@ -17,5 +17,5 @@
 	int     nods;
 	double  mindistance;
-	SeqVec<IssmPDouble>*     flags;
+	IssmSeqVec<IssmPDouble>*     flags;
 
 	/*recover handle and gate: */
@@ -49,5 +49,5 @@
 		/*display current iteration*/
 		if (my_thread==0 && fmod((double)i,(double)100)==0)
-		 _printString_("\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)
-	 _printLine_("\r      loop progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+	 _printf_("\r      loop progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
 
 	/*Free ressources:*/
Index: /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp
===================================================================
--- /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp	(revision 15396)
@@ -5,8 +5,5 @@
 #include "./PositiveDegreeDayx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void PositiveDegreeDayx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters){
@@ -57,5 +54,5 @@
 
   if (itm >= NPDMAX){
-    _printLine_("increase NPDMAX in massBalance.cpp");
+    _printf_("increase NPDMAX in massBalance.cpp\n");
     exit (1);
       }
@@ -83,5 +80,5 @@
   itm = reCast<int,IssmDouble>((PDCUT+2.*siglimc)/DT + 1.5);
   if (itm >= NPDCMAX){
-    _printLine_("'increase NPDCMAX in p35com'");
+    _printf_("'increase NPDCMAX in p35com'\n");
     exit (1);
       }
Index: /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.h
===================================================================
--- /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _POSITIVEDEGREEDAYX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp
===================================================================
--- /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp	(revision 15396)
@@ -5,5 +5,4 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
 
Index: /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h
===================================================================
--- /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h	(revision 15396)
@@ -5,5 +5,5 @@
 #define _PROPAGATEFLAGSFROMCONNECTIVITYX_H
 
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 15396)
@@ -10,5 +10,5 @@
 
 #include "./Reduceloadx.h"
-#include "../../io/io.h"
+#include "../../shared/io/io.h"
 
 void	Reduceloadx( Vector<IssmDouble>* pf, Matrix<IssmDouble>* Kfs, Vector<IssmDouble>* y_s,bool flag_ys0){
@@ -22,5 +22,5 @@
 	bool        oldalloc  = false;
 
-	if(VerboseModule()) _pprintLine_("   Dirichlet lifting applied to load vector");
+	if(VerboseModule()) _printf0_("   Dirichlet lifting applied to load vector\n");
 
 	Kfs->GetSize(&global_m,&global_n);
@@ -54,6 +54,6 @@
 
 	/*Free ressources and return*/
-	xdelete(&y_s0);
-	xdelete(&Kfsy_s);
+	delete y_s0;
+	delete Kfsy_s;
 
 }
Index: /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.h
===================================================================
--- /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _REDUCELOADX_H
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 15396)
@@ -16,4 +16,6 @@
 	IssmDouble *ug_serial = NULL;
 	bool        oldalloc  = false;
+
+	if(VerboseModule()) _printf0_("   Reduce vector from g to f set\n");
 
 	/*first figure out fsize: */
Index: /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 15396)
@@ -7,5 +7,5 @@
 #define _REDUCEVECTORGTOFX_H
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h	(revision 15396)
@@ -7,5 +7,5 @@
 #define _REDUCEVECTORGTOSX_H
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 15396)
@@ -3,11 +3,14 @@
  */
 
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
 #include "./ResetConstraintsx.h"
-#include "../modules.h"
 #include "../../shared/shared.h"
-#include "../../io/io.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../ConstraintsStatex/ConstraintsStatex.h"
 
 void ResetConstraintsx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters){
@@ -17,5 +20,5 @@
 
 	/*Display message*/
-	if(VerboseModule()) _pprintLine_("   Resetting penalties");
+	if(VerboseModule()) _printf0_("   Resetting penalties\n");
 
 	/*recover parameters: */
@@ -24,11 +27,14 @@
 	/*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)){
 		_error_("rift constraints reset not supported yet!");
 	}
-	else if(ThermalIsPresent(loads,analysis_type)){
+	#endif
+	#ifdef _HAVE_THERMAL_
+	if(ThermalIsPresent(loads,analysis_type)){
 		ThermalConstraintsReset(loads,analysis_type);
 	}
-	else{ /*Do nothing, no constraints management!:*/}
+	#endif
 
 }
Index: /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _RESETCONSTRAINTSX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp	(revision 15396)
@@ -5,5 +5,4 @@
 #include "./ResetCoordinateSystemx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
 
Index: /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h
===================================================================
--- /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _RESETCOORDINATESYSTEMX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 15396)
@@ -6,9 +6,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
-void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters, int weight_index){
 
 	/*Intermediary*/
@@ -23,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->RheologyBbarAbsGradient(process_units,weight_index);
+		J+=element->RheologyBbarAbsGradient(weight_index);
 	}
 
Index: /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _RHEOLOGYBBARGRADIENTX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/Scotchx/Scotchx.h
===================================================================
--- /issm/trunk/src/c/modules/Scotchx/Scotchx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Scotchx/Scotchx.h	(revision 15396)
@@ -17,7 +17,5 @@
 #include <stdio.h>
 #include <string.h>
-
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 #ifdef _HAVE_SCOTCH_ //only works if scotch library has been compiled in.
Index: /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 #include "./SetControlInputsFromVectorx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* vector){
Index: /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h
===================================================================
--- /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 15396)
@@ -5,6 +5,5 @@
 #define _SETCONTROLINPUTSXFROMVECTOR_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Shp2Expx/Shp2Expx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Shp2Expx/Shp2Expx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Shp2Expx/Shp2Expx.cpp	(revision 15396)
@@ -5,9 +5,6 @@
 #include "./Shp2Expx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../modules.h"
+#include "../../kml/kmlobjects.h"
 
 int Shp2Expx(char* filshp,char* filexp){
@@ -80,5 +77,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_pprintString_("\nShp2Expx Module -- " << ctime(&time0));
+	_printf0_("\nShp2Expx Module -- " << ctime(&time0));
 
 /*  note that much of the following code is taken from shpdump.c in shapelib.  */
@@ -299,9 +296,7 @@
 
 			if (pnpart[i] > 0)
-				_printf_(true,"Warning -- Shape %d of type \"%s\" should not have %d > 0 parts.\n",
-						 i,SHPTypeName( pstype[i] ),pnpart[i]);
+				_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" should not have " << pnpart[i] << " > 0 parts.\n\n");
 			if (pnvert[i] > 1)
-				_printf_(true,"Warning -- Shape %d of type \"%s\" should not have %d > 1 vertices.\n",
-						 i,SHPTypeName( pstype[i] ),pnvert[i]);
+				_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" should not have " << pnvert[i] << " > 1 vertices.\n\n");
 
 			kpoint=new KML_Point();
@@ -470,6 +465,5 @@
 				else {
 					if (!kpoly) {
-						_printf_(true,"Warning -- Shape %d of type \"%s\", part %d, expected to be outer loop (cw).\n",
-								 i,SHPTypeName( pstype[i] ),j);
+						_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\", part " << j << ", expected to be outer loop (cw).\n\n");
 						continue;
 					}
@@ -519,6 +513,5 @@
 
 			if (pnpart[i] > 0)
-				_printf_(true,"Warning -- Shape %d of type \"%s\" should not have %d > 0 parts.\n",
-						 i,SHPTypeName( pstype[i] ),pnpart[i]);
+				_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" should not have " << pnpart[i] << " > 0 parts.\n\n");
 
 /*  create a multigeometry to hold all the points  */
@@ -563,6 +556,5 @@
 
 		else if (pstype[i] == SHPT_MULTIPATCH) {
-			_printf_(true,"Warning -- Shape %d of type \"%s\" will be ignored.\n",
-					 i,SHPTypeName( pstype[i] ));
+			_printf_("Warning -- Shape " << i << " of type \"" <<SHPTypeName( pstype[i] ) << "\" will be ignored.\n\n");
 			continue;
 		}
@@ -571,6 +563,5 @@
 
 		else {
-			_printf_(true,"Warning -- Shape %d of type \"%s\" will be ignored.\n",
-					 i,SHPTypeName( pstype[i] ));
+			_printf_("Warning -- Shape " << i << " of type \"" <<SHPTypeName( pstype[i] ) << "\" will be ignored.\n\n");
 		}
 	}
@@ -585,5 +576,5 @@
 /*  open exp file  */
 
-	_pprintLine_("Writing exp profiles to file.");
+	_printf0_("Writing exp profiles to file.\n");
 	fid=fopen(filexp,"w");
 
@@ -619,6 +610,5 @@
 	clock1=clock();
 	time1 =time(NULL);
-	_printf_(true,"Shp2Expx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
-			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+	_printf_("Shp2Expx Module -- " <<((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " <<difftime(time1,time0)  << " elapsed seconds.\n\n\n");
 
 	return(iret);
Index: /issm/trunk/src/c/modules/Shp2Expx/Shp2Expx.h
===================================================================
--- /issm/trunk/src/c/modules/Shp2Expx/Shp2Expx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Shp2Expx/Shp2Expx.h	(revision 15396)
@@ -18,6 +18,5 @@
 #endif
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 15396)
@@ -5,9 +5,6 @@
 #include "./Shp2Kmlx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../modules.h"
+#include "../../kml/kmlobjects.h"
 
 int Shp2Kmlx(char* filshp,char* filkml,
@@ -68,5 +65,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_pprintString_("\nShp2Kmlx Module -- " << ctime(&time0));
+	_printf0_("\nShp2Kmlx Module -- " << ctime(&time0));
 
 /*  note that much of the following code is taken from shpdump.c in shapelib.  */
@@ -287,9 +284,7 @@
 
 			if (pnpart[i] > 0)
-				_printf_(true,"Warning -- Shape %d of type \"%s\" should not have %d > 0 parts.\n",
-						 i,SHPTypeName( pstype[i] ),pnpart[i]);
+				_printf_("Warning -- Shape "<< i << " of type \"" << SHPTypeName( pstype[i] ) << "\" should not have " << pnpart[i] << " > 0 parts.\n\n");
 			if (pnvert[i] > 1)
-				_printf_(true,"Warning -- Shape %d of type \"%s\" should not have %d > 1 vertices.\n",
-						 i,SHPTypeName( pstype[i] ),pnvert[i]);
+				_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" should not have " << pnpart[i] << " > 1 vertices.\n\n");
 
 			kpoint=new KML_Point();
@@ -458,6 +453,5 @@
 				else {
 					if (!kpoly) {
-						_printf_(true,"Warning -- Shape %d of type \"%s\", part %d, expected to be outer loop (cw).\n",
-								 i,SHPTypeName( pstype[i] ),j);
+						_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\", part " << j << ", expected to be outer loop (cw).\n\n");
 						continue;
 					}
@@ -507,6 +501,5 @@
 
 			if (pnpart[i] > 0)
-				_printf_(true,"Warning -- Shape %d of type \"%s\" should not have %d > 0 parts.\n",
-						 i,SHPTypeName( pstype[i] ),pnpart[i]);
+				_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" should not have " << pnpart[i] << " > 0 parts.\n\n");
 
 /*  create a multigeometry to hold all the points  */
@@ -551,6 +544,5 @@
 
 		else if (pstype[i] == SHPT_MULTIPATCH) {
-			_printf_(true,"Warning -- Shape %d of type \"%s\" will be ignored.\n",
-					 i,SHPTypeName( pstype[i] ));
+			_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" will be ignored.\n\n");
 			continue;
 		}
@@ -559,6 +551,5 @@
 
 		else {
-			_printf_(true,"Warning -- Shape %d of type \"%s\" will be ignored.\n",
-					 i,SHPTypeName( pstype[i] ));
+			_printf_("Warning -- Shape " << i << " of type \"" << SHPTypeName( pstype[i] ) << "\" will be ignored.\n\n");
 		}
 	}
@@ -573,5 +564,5 @@
 /*  write kml file  */
 
-	_pprintLine_("Writing kml document to file.");
+	_printf0_("Writing kml document to file.\n");
 	fid=fopen(filkml,"w");
 	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
@@ -602,6 +593,5 @@
 	clock1=clock();
 	time1 =time(NULL);
-	_printf_(true,"Shp2Kmlx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
-			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+	_printf_("Shp2Kmlx Module -- " << ((double)(clock1-clock0))/CLOCKS_PER_SEC << " CPU seconds; " << difftime(time1,time0) << " elapsed seconds.\n\n\n");
 
 	return(iret);
Index: /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.h
===================================================================
--- /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.h	(revision 15396)
@@ -18,6 +18,5 @@
 #endif
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.cpp	(revision 15396)
@@ -5,8 +5,5 @@
 #include "./SmbGradientsx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void SmbGradientsx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters){
Index: /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.h
===================================================================
--- /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _SMBGRADIENTSX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Solverx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Solverx/CMakeLists.txt	(revision 15395)
+++ /issm/trunk/src/c/modules/Solverx/CMakeLists.txt	(revision 15396)
@@ -5,5 +5,4 @@
 # }}}
 # CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/Solverx/Solverx.cpp
-              $ENV{ISSM_DIR}/src/c/modules/Solverx/SolverxSeq.cpp PARENT_SCOPE)
+set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/Solverx/Solverx.cpp PARENT_SCOPE)
 # }}}
Index: sm/trunk/src/c/modules/Solverx/DofTypesToIndexSet.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/DofTypesToIndexSet.cpp	(revision 15395)
+++ 	(revision )
@@ -1,82 +1,0 @@
-/*!\file Solverx
- * \brief solver
- */
-
-#include "./Solverx.h"
-#include "../../shared/shared.h"
-#include "../../include/include.h"
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-void DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum){
-
-	/*output: */
-	IS          isv=NULL;
-	IS          isp=NULL;
-
-	int         start,end;
-	IssmDouble*     df_local=NULL;
-	int         df_local_size;
-	int         i;
-
-	int*     pressure_indices=NULL;
-	int*     velocity_indices=NULL;
-	int      pressure_num=0;
-	int      velocity_num=0;
-	int      pressure_count=0;
-	int      velocity_count=0;
-
-	if(typeenum==StokesSolverEnum){
-
-		/*Ok, recover doftypes vector values and indices: */
-		VecGetOwnershipRange(df,&start,&end);
-		VecGetLocalSize(df,&df_local_size);
-		VecGetArray(df,&df_local);
-
-		pressure_num=0;
-		velocity_num=0;
-		for(i=0;i<df_local_size;i++){
-			if (df_local[i]==PressureEnum)pressure_num++;
-			else velocity_num++;
-		}
-
-		/*Allocate indices: */
-		if(pressure_num)pressure_indices=xNew<int>(pressure_num);
-		if(velocity_num)velocity_indices=xNew<int>(velocity_num);
-
-		pressure_count=0;
-		velocity_count=0;
-		for(i=0;i<df_local_size;i++){
-			if (df_local[i]==PressureEnum){
-				pressure_indices[pressure_count]=start+i;
-				pressure_count++;
-			}
-			if (df_local[i]==VelocityEnum){
-				velocity_indices[velocity_count]=start+i;
-				velocity_count++;
-			}
-		}
-		VecRestoreArray(df,&df_local);
-
-		/*Create indices sets: */
-		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
-		ISCreateGeneral(IssmComm::GetComm(),pressure_num,pressure_indices,&isp);
-		ISCreateGeneral(IssmComm::GetComm(),velocity_num,velocity_indices,&isv);
-		#else
-		ISCreateGeneral(IssmComm::GetComm(),pressure_num,pressure_indices,PETSC_COPY_VALUES,&isp);
-		ISCreateGeneral(IssmComm::GetComm(),velocity_num,velocity_indices,PETSC_COPY_VALUES,&isv);
-		#endif
-	}
-
-	/*Free ressources:*/
-	xDelete<int>(pressure_indices);
-	xDelete<int>(velocity_indices);
-
-	/*Assign output pointers:*/
-	*pisv=isv;
-	*pisp=isp;
-}
Index: /issm/trunk/src/c/modules/Solverx/Solverx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/Solverx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/Solverx/Solverx.cpp	(revision 15396)
@@ -2,9 +2,4 @@
  * \brief solver
  */
-
-#include "./Solverx.h"
-#include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 
 #ifdef HAVE_CONFIG_H
@@ -14,35 +9,25 @@
 #endif
 
+#include "./Solverx.h"
+#include "../../shared/shared.h"
+
 void	Solverx(Vector<IssmDouble>** puf, Matrix<IssmDouble>* Kff, Vector<IssmDouble>* pf, Vector<IssmDouble>* uf0,Vector<IssmDouble>* df, Parameters* parameters){
+
+	/*intermediary: */
+	Solver<IssmDouble> *solver=NULL;
 
 	/*output: */
 	Vector<IssmDouble> *uf=NULL;
 
-	/*In debugging mode, check that stiffness matrix and load vectors are not NULL (they can be empty)*/
-	_assert_(Kff);
-	_assert_(pf);
+	if(VerboseModule()) _printf0_("   Solving matrix system\n");
 
-	/*Initialize vector: */
-	uf=new Vector<IssmDouble>();
+	/*Initialize solver: */
+	solver=new Solver<IssmDouble>(Kff,pf,uf0,df,parameters);
 
-	/*According to matrix type, use specific solvers: */
-	switch(Kff->type){
-		#ifdef _HAVE_PETSC_
-		case PetscMatType:{
-			PetscVec* uf0_vector = NULL;
-			PetscVec* df_vector  = NULL;
-			if(uf0) uf0_vector = uf0->pvector;
-			if(df)  df_vector  = df->pvector;
-			SolverxPetsc(&uf->pvector,Kff->pmatrix,pf->pvector,uf0_vector,df_vector,parameters);
-			break;}
-		#endif
-		case SeqMatType:{
-			SolverxSeq(&uf->svector,Kff->smatrix,pf->svector,parameters);
-			break;}
-		default:
-			  _error_("Matrix type: " << Kff->type << " not supported yet!");
-	}
+	/*Solve:*/
+	uf=solver->Solve();
 
-	/*Assign output pointers:*/
+	/*clean up and assign output pointers:*/
+	delete solver;
 	*puf=uf;
 }
Index: /issm/trunk/src/c/modules/Solverx/Solverx.h
===================================================================
--- /issm/trunk/src/c/modules/Solverx/Solverx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/Solverx/Solverx.h	(revision 15396)
@@ -12,28 +12,8 @@
 #endif
 
-#include "../../classes/objects/objects.h"
+#include "../../toolkits/toolkits.h"
 
 /* local prototypes: */
 void	Solverx(Vector<IssmDouble>** puf, Matrix<IssmDouble>* Kff, Vector<IssmDouble>* pf, Vector<IssmDouble>* uf0,Vector<IssmDouble>* df, Parameters* parameters);
 
-#ifdef _HAVE_PETSC_
-void	SolverxPetsc(PetscVec** puf, PetscMat* Kff, PetscVec* pf, PetscVec* uf0,PetscVec* df, Parameters* parameters);
-void	SolverxPetsc(Vec* puf, Mat Kff, Vec pf, Vec uf0,Vec df, Parameters* parameters);
-void  DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum);
-#endif
-
-void SolverxSeq(SeqVec<IssmDouble>** puf,SeqMat<IssmDouble>* Kff, SeqVec<IssmDouble>* pf,Parameters* parameters);
-void SolverxSeq(IssmPDouble **pX, IssmPDouble *A, IssmPDouble *B,int n);
-void SolverxSeq(IssmPDouble *X, IssmPDouble *A, IssmPDouble *B,int n);
-
-#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
-void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters);
-// call back functions:
-ADOLC_ext_fct EDF_for_solverx;
-ADOLC_ext_fct_fos_forward EDF_fos_forward_for_solverx;
-ADOLC_ext_fct_fos_reverse EDF_fos_reverse_for_solverx;
-ADOLC_ext_fct_fov_forward EDF_fov_forward_for_solverx;
-ADOLC_ext_fct_fov_reverse EDF_fov_reverse_for_solverx;
-#endif
-
 #endif  /* _SOLVERX_H */
Index: sm/trunk/src/c/modules/Solverx/SolverxPetsc.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/SolverxPetsc.cpp	(revision 15395)
+++ 	(revision )
@@ -1,159 +1,0 @@
-/*!\file SolverxPetsc
- * \brief Petsc implementation of solver
- */
-
-#include "./Solverx.h"
-#include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-void	SolverxPetsc(PetscVec** puf, PetscMat* Kff, PetscVec* pf, PetscVec* uf0,PetscVec* df, Parameters* parameters){
-
-	PetscVec* uf=new PetscVec();
-
-	Vec uf0_vector = NULL;
-	Vec df_vector  = NULL;
-
-	if(uf0) uf0_vector = uf0->vector;
-	if(df)  df_vector  = df->vector;
-
-	SolverxPetsc(&uf->vector, Kff->matrix, pf->vector, uf0_vector, df_vector, parameters);
-
-	*puf=uf;
-
-}
-void	SolverxPetsc(Vec* puf, Mat Kff, Vec pf, Vec uf0,Vec df, Parameters* parameters){
-
-	/*Output: */
-	Vec        uf               = NULL;
-
-	/*Intermediary: */
-	int        local_m,local_n,global_m,global_n;
-
-	/*Solver */
-	KSP        ksp              = NULL;
-	PC         pc               = NULL;
-	int        iteration_number;
-	int        solver_type;
-	bool       fromlocalsize    = true;
-	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
-	PetscTruth flag,flg;
-	#else
-	PetscBool flag,flg;
-	#endif
-
-	/*Stokes: */
-	IS         isv=NULL;
-	IS         isp=NULL;
-
-	#if _PETSC_MAJOR_ >= 3 
-	char ksp_type[50];
-	#endif
-
-	/*Display message*/
-	if(VerboseModule()) _pprintLine_("   Solving");
-	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
-	if(VerboseSolver())PetscOptionsPrint(stdout);
-	#else
-	if(VerboseSolver())PetscOptionsView(PETSC_VIEWER_STDOUT_WORLD);
-	#endif
-
-	/*First, check that f-set is not NULL, i.e. model is fully constrained:*/ 
-	_assert_(Kff);
-	MatGetSize(Kff,&global_m,&global_n); _assert_(global_m==global_m);
-	if(!global_n){
-		*puf=NewVec(0,IssmComm::GetComm()); return;
-	}
-
-	/*Initial guess */
-	/*Now, check that we are not giving an initial guess to the solver, if we are running a direct solver: */
-	#if _PETSC_MAJOR_ >= 3 
-	PetscOptionsGetString(PETSC_NULL,"-ksp_type",ksp_type,49,&flg);
-	if (strcmp(ksp_type,"preonly")==0)uf0=NULL;
-	#endif
-
-	/*If initial guess for the solution exists, use it to create uf, otherwise, 
-	 * duplicate the right hand side so that the solution vector has the same structure*/
-	if(uf0){
-		VecDuplicate(uf0,&uf); VecCopy(uf0,uf);
-	}
-	else{
-		MatGetLocalSize(Kff,&local_m,&local_n);uf=NewVec(local_n,IssmComm::GetComm(),fromlocalsize);
-	}
-
-	/*Process petsc options to see if we are using special types of external solvers*/
-	PetscOptionsDetermineSolverType(&solver_type);
-
-	/*Check the solver is available*/
-	if(solver_type==MUMPSPACKAGE_LU || solver_type==MUMPSPACKAGE_CHOL){
-		#if _PETSC_MAJOR_ >=3
-			#ifndef _HAVE_MUMPS_
-			_error_("requested MUMPS solver, which was not compiled into ISSM!\n");
-			#endif
-		#endif
-	}
-
-	/*Prepare solver*/
-	KSPCreate(IssmComm::GetComm(),&ksp);
-	KSPSetOperators(ksp,Kff,Kff,DIFFERENT_NONZERO_PATTERN);
-	KSPSetFromOptions(ksp);
-
-	#if _PETSC_MAJOR_==3
-	/*Specific solver?: */
-	KSPGetPC(ksp,&pc);
-	if (solver_type==MUMPSPACKAGE_LU){
-		#if _PETSC_MINOR_==1
-		PCFactorSetMatSolverPackage(pc,MAT_SOLVER_MUMPS);
-		#else
-		PCFactorSetMatSolverPackage(pc,MATSOLVERMUMPS);
-		#endif
-	}
-
-	/*Stokes: */
-	if (solver_type==StokesSolverEnum){
-		/*Make indices out of doftypes: */
-		if(!df)_error_("need doftypes for Stokes solver!\n");
-		DofTypesToIndexSet(&isv,&isp,df,StokesSolverEnum);
-
-		/*Set field splits: */
-		KSPGetPC(ksp,&pc);
-		#if _PETSC_MINOR_==1
-		PCFieldSplitSetIS(pc,isv);
-		PCFieldSplitSetIS(pc,isp);
-		#else
-		PCFieldSplitSetIS(pc,PETSC_NULL,isv);
-		PCFieldSplitSetIS(pc,PETSC_NULL,isp);
-		#endif
-
-	}
-	#endif
-
-	/*If there is an initial guess for the solution, use it
-	 * except if we are using the MUMPS direct solver
-	 * where any initial guess will crash Petsc*/
-	if (uf0){
-		if((solver_type!=MUMPSPACKAGE_LU) && (solver_type!=MUMPSPACKAGE_CHOL) && (solver_type!=SPOOLESPACKAGE_LU) && (solver_type!=SPOOLESPACKAGE_CHOL) && (solver_type!=SUPERLUDISTPACKAGE)){
-			KSPSetInitialGuessNonzero(ksp,PETSC_TRUE);
-		}
-	}
-
-	/*Solve: */
-	if(VerboseSolver())KSPView(ksp,PETSC_VIEWER_STDOUT_WORLD);
-	KSPSolve(ksp,pf,uf);
-
-	/*Check convergence*/
-	KSPGetIterationNumber(ksp,&iteration_number);
-	if (iteration_number<0) _error_("Solver diverged at iteration number: " << -iteration_number);
-
-	/*Free resources:*/
-	KSPFree(&ksp);
-
-	/*Assign output pointers:*/
-	*puf=uf;
-}
Index: sm/trunk/src/c/modules/Solverx/SolverxSeq.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/SolverxSeq.cpp	(revision 15395)
+++ 	(revision )
@@ -1,249 +1,0 @@
-/*!\file SolverxSeq
- * \brief implementation of sequential solver using the GSL librarie
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-#include <cstring>
-
-#include "./Solverx.h"
-#include "../../shared/shared.h"
-#include "../../classes/classes.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
-
-#ifdef _HAVE_GSL_
-#include <gsl/gsl_linalg.h>
-#endif
-
-void SolverxSeq(SeqVec<IssmDouble>** puf,SeqMat<IssmDouble>* Kff, SeqVec<IssmDouble>* pf, Parameters* parameters){/*{{{*/
-
-#ifdef _HAVE_GSL_
-	/*Intermediary: */
-	int M,N,N2;
-	SeqVec<IssmDouble> *uf = NULL;
-
-	Kff->GetSize(&M,&N);
-	pf->GetSize(&N2);
-
-	if(N!=N2)_error_("Right hand side vector of size " << N2 << ", when matrix is of size " << M << "-" << N << " !");
-	if(M!=N)_error_("Stiffness matrix should be square!");
-#ifdef _HAVE_ADOLC_
-	ensureContiguousLocations(N);
-#endif
-	IssmDouble *x  = xNew<IssmDouble>(N);
-#ifdef _HAVE_ADOLC_
-	SolverxSeq(x,Kff->matrix,pf->vector,N,parameters);
-#else
-	SolverxSeq(x,Kff->matrix,pf->vector,N);
-#endif
-
-	uf=new SeqVec<IssmDouble>(x,N);
-	xDelete(x);
-
-	/*Assign output pointers:*/
-	*puf=uf;
-
-#else
-	_error_("GSL support not compiled in!");
-#endif
-
-}/*}}}*/
-void SolverxSeq(IssmPDouble **pX, IssmPDouble *A, IssmPDouble *B,int n){ /*{{{*/
-
-	/*Allocate output*/
-	double* X = xNew<double>(n); 
-
-	/*Solve*/
-	SolverxSeq(X,A,B,n);
-
-	/*Assign output pointer*/
-	*pX=X;
-}
-/*}}}*/
-
-#ifdef _HAVE_ADOLC_
-int EDF_for_solverx(int n, IssmPDouble *x, int m, IssmPDouble *y){ /*{{{*/
-	SolverxSeq(y,x, x+m*m, m); // x is where the matrix starts, x+m*m is where the right-hand side starts
-	return 0;
-} /*}}}*/
-int EDF_fos_forward_for_solverx(int n, IssmPDouble *inVal, IssmPDouble *inDeriv, int m, IssmPDouble *outVal, IssmPDouble *outDeriv) { /*{{{*/
-#ifdef _HAVE_GSL_
-	//  for (int i=0; i<m*m; ++i) std::cout << "EDF_fos_forward_for_solverx A["<< i << "]=" << inVal[i] << std::endl;
-	//  for (int i=0; i<m; ++i) std::cout << "EDF_fos_forward_for_solverx b["<< i << "]=" << inVal[i+m*m] << std::endl;
-	// the matrix will be modified by LU decomposition. Use gsl_A copy
-	double* Acopy = xNew<double>(m*m);
-	xMemCpy(Acopy,inVal,m*m);
-	/*Initialize gsl matrices and vectors: */
-	gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
-	gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
-	gsl_permutation *perm_p = gsl_permutation_alloc (m);
-	int  signPerm;
-	// factorize
-	gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
-	gsl_vector *gsl_x_p = gsl_vector_alloc (m);
-	// solve for the value
-	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
-	/*Copy result*/
-	xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
-	gsl_vector_free(gsl_x_p);
-	//  for (int i=0; i<m; ++i) std::cout << "EDF_fos_forward_for_solverx x["<< i << "]=" << outVal[i] << std::endl;
-	// solve for the derivatives acc. to A * dx = r  with r=db - dA * x
-	// compute the RHS
-	double* r=xNew<double>(m);
-	for (int i=0; i<m; i++) {
-		r[i]=inDeriv[m*m+i]; // this is db[i]
-		for (int j=0;j<m; j++) {
-			r[i]-=inDeriv[i*m+j]*outVal[j]; // this is dA[i][j]*x[j]
-		}
-	}
-	gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
-	gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
-	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
-	xMemCpy(outDeriv,gsl_vector_ptr(gsl_dx_p,0),m);
-	gsl_vector_free(gsl_dx_p);
-	xDelete(r);
-	gsl_permutation_free(perm_p);
-	xDelete(Acopy);
-#endif
-	return 0;
-} /*}}}*/
-int EDF_fov_forward_for_solverx(int n, IssmPDouble *inVal, int directionCount, IssmPDouble **inDeriv, int m, IssmPDouble *outVal, IssmPDouble **outDeriv) { /*{{{*/
-#ifdef _HAVE_GSL_
-	// the matrix will be modified by LU decomposition. Use gsl_A copy
-	double* Acopy = xNew<double>(m*m);
-	xMemCpy(Acopy,inVal,m*m);
-	/*Initialize gsl matrices and vectors: */
-	gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
-	gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
-	gsl_permutation *perm_p = gsl_permutation_alloc (m);
-	int  signPerm;
-	// factorize
-	gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
-	gsl_vector *gsl_x_p = gsl_vector_alloc (m);
-	// solve for the value
-	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
-	/*Copy result*/
-	xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
-	gsl_vector_free(gsl_x_p);
-	// solve for the derivatives acc. to A * dx = r  with r=db - dA * x
-	double* r=xNew<double>(m);
-	gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
-	for (int dir=0;dir<directionCount;++dir) {
-		// compute the RHS
-		for (int i=0; i<m; i++) {
-			r[i]=inDeriv[m*m+i][dir]; // this is db[i]
-			for (int j=0;j<m; j++) {
-				r[i]-=inDeriv[i*m+j][dir]*outVal[j]; // this is dA[i][j]*x[j]
-			}
-		}
-		gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
-		gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
-		// reuse r
-		xMemCpy(r,gsl_vector_ptr(gsl_dx_p,0),m);
-		for (int i=0; i<m; i++) {
-			outDeriv[i][dir]=r[i];
-		}
-	}
-	gsl_vector_free(gsl_dx_p);
-	xDelete(r);
-	gsl_permutation_free(perm_p);
-	xDelete(Acopy);
-#endif
-	return 0;
-}
-/*}}}*/
-int EDF_fos_reverse_for_solverx(int m, double *dp_U, int n, double *dp_Z, double* dp_x, double* dp_y) { /*{{{*/
-	// copy to transpose the matrix
-	double* transposed=xNew<double>(m*m);
-	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) transposed[j*m+i]=dp_x[i*m+j];
-	gsl_matrix_view aTransposed = gsl_matrix_view_array (transposed,m,m);
-	// the adjoint of the solution is our right-hand side
-	gsl_vector_view x_bar=gsl_vector_view_array(dp_U,m);
-	// the last m elements of dp_Z representing the adjoint of the right-hand side we want to compute:
-	gsl_vector_view b_bar=gsl_vector_view_array(dp_Z+m*m,m);
-	gsl_permutation *perm_p = gsl_permutation_alloc (m);
-	int permSign;
-	gsl_linalg_LU_decomp (&aTransposed.matrix, perm_p, &permSign);
-	gsl_linalg_LU_solve (&aTransposed.matrix, perm_p, &x_bar.vector, &b_bar.vector);
-	// now do the adjoint of the matrix
-	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) dp_Z[i*m+j]-=dp_Z[m*m+i]*dp_y[j];
-	gsl_permutation_free(perm_p);
-	xDelete(transposed);
-	return 0;
-}
-/*}}}*/
-int EDF_fov_reverse_for_solverx(int m, int p, double **dpp_U, int n, double **dpp_Z, double* dp_x, double* dp_y) { /*{{{*/
-	// copy to transpose the matrix
-	double* transposed=xNew<double>(m*m);
-	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) transposed[j*m+i]=dp_x[i*m+j];
-	gsl_matrix_view aTransposed = gsl_matrix_view_array (transposed,m,m);
-	gsl_permutation *perm_p = gsl_permutation_alloc (m);
-	int permSign;
-	gsl_linalg_LU_decomp (&aTransposed.matrix, perm_p, &permSign);
-	for (int weightsRowIndex=0;weightsRowIndex<p;++weightsRowIndex) {
-		// the adjoint of the solution is our right-hand side
-		gsl_vector_view x_bar=gsl_vector_view_array(dpp_U[weightsRowIndex],m);
-		// the last m elements of dp_Z representing the adjoint of the right-hand side we want to compute:
-		gsl_vector_view b_bar=gsl_vector_view_array(dpp_Z[weightsRowIndex]+m*m,m);
-		gsl_linalg_LU_solve (&aTransposed.matrix, perm_p, &x_bar.vector, &b_bar.vector);
-		// now do the adjoint of the matrix
-		for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) dpp_Z[weightsRowIndex][i*m+j]-=dpp_Z[weightsRowIndex][m*m+i]*dp_y[j];
-	}
-	gsl_permutation_free(perm_p);
-	xDelete(transposed);
-	return 0;
-}
-/*}}}*/
-void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters){/*{{{*/
-	// pack inputs to conform to the EDF-prescribed interface
-        // ensure a contiguous block of locations:
-        ensureContiguousLocations(n*(n+1));
-        IssmDouble*  adoubleEDFin=xNew<IssmDouble>(n*(n+1));  // packed inputs, i.e. matrix and right hand side
-        for(int i=0; i<n*n;i++)adoubleEDFin[i]    =A[i];      // pack matrix
-        for(int i=0; i<n;  i++)adoubleEDFin[i+n*n]=B[i];      // pack the right hand side
-        IssmPDouble* pdoubleEDFin=xNew<IssmPDouble>(n*(n+1)); // provide space to transfer inputs during call_ext_fct
-	IssmPDouble* pdoubleEDFout=xNew<IssmPDouble>(n);           // provide space to transfer outputs during call_ext_fct
-	// call the wrapped solver through the registry entry we retrieve from parameters
-	call_ext_fct(dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
-	             n*(n+1), pdoubleEDFin, adoubleEDFin,
-	             n, pdoubleEDFout,X);
-	// for(int i=0; i<n;  i++) {ADOLC_DUMP_MACRO(X[i]);}
-	xDelete(adoubleEDFin);
-	xDelete(pdoubleEDFin);
-	xDelete(pdoubleEDFout);
-}
-/*}}}*/
-#endif
-void SolverxSeq(IssmPDouble *X, IssmPDouble *A, IssmPDouble *B,int n){ /*{{{*/
-#ifdef _HAVE_GSL_
-	/*GSL Matrices and vectors: */
-	int              s;
-	gsl_matrix_view  a;
-	gsl_vector_view  b,x;
-	gsl_permutation *p = NULL;
-//	for (int i=0; i<n*n; ++i) std::cout << "SolverxSeq A["<< i << "]=" << A[i] << std::endl;
-//	for (int i=0; i<n; ++i) std::cout << "SolverxSeq b["<< i << "]=" << B[i] << std::endl;
-	/*A will be modified by LU decomposition. Use copy*/
-	double* Acopy = xNew<double>(n*n);
-	xMemCpy(Acopy,A,n*n);
-
-	/*Initialize gsl matrices and vectors: */
-	a = gsl_matrix_view_array (Acopy,n,n);
-	b = gsl_vector_view_array (B,n);
-	x = gsl_vector_view_array (X,n);
-
-	/*Run LU and solve: */
-	p = gsl_permutation_alloc (n);
-	gsl_linalg_LU_decomp (&a.matrix, p, &s);
-	gsl_linalg_LU_solve (&a.matrix, p, &b.vector, &x.vector);
-
-	/*Clean up and assign output pointer*/
-	xDelete(Acopy);
-	gsl_permutation_free(p);
-#endif
-}
-/*}}}*/
Index: /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.cpp	(revision 15396)
@@ -6,7 +6,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void SpcNodesx(Nodes* nodes,Constraints* constraints,Parameters* parameters, int analysis_type){
Index: /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.h
===================================================================
--- /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _SPCNODESX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 #include "../../toolkits/toolkits.h"
 
Index: /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 15396)
@@ -6,9 +6,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
 
 	/*Intermediary*/
@@ -23,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->SurfaceAbsVelMisfit(process_units,weight_index);
+		J+=element->SurfaceAbsVelMisfit(weight_index);
 	}
 
Index: /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _SURFACEABSVELMISFITX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 15396)
@@ -6,7 +6,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 #include "../InputUpdateFromConstantx/InputUpdateFromConstantx.h"
 
Index: /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _SURFACEAREAX_H
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 15396)
@@ -6,10 +6,8 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 #include "../SurfaceAreax/SurfaceAreax.h"
 
-void SurfaceAverageVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceAverageVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
 
 	/*Intermediary*/
@@ -27,5 +25,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->SurfaceAverageVelMisfit(process_units,weight_index);
+		J+=element->SurfaceAverageVelMisfit(weight_index);
 	}
 
Index: /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _SURFACEAVERAGEVELMISFITX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void SurfaceAverageVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceAverageVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 15396)
@@ -6,9 +6,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
 
 	/*Intermediary*/
@@ -23,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->SurfaceLogVelMisfit(process_units,weight_index);
+		J+=element->SurfaceLogVelMisfit(weight_index);
 	}
 
Index: /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _SURFACELOGVELMISFITX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 15396)
@@ -6,9 +6,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
 
 	/*Intermediary*/
@@ -23,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->SurfaceLogVxVyMisfit(process_units,weight_index);
+		J+=element->SurfaceLogVxVyMisfit(weight_index);
 	}
 
Index: /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _SURFACELOGVXVYMISFITX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 15396)
@@ -6,9 +6,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
 
 	/*Intermediary*/
@@ -23,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->SurfaceRelVelMisfit(process_units,weight_index);
+		J+=element->SurfaceRelVelMisfit(weight_index);
 	}
 
Index: /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _SURFACERELVELMISFITX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 15396)
@@ -6,9 +6,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters, int weight_index){
 
 	/*Intermediary*/
@@ -23,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->ThicknessAbsMisfit(process_units,weight_index);
+		J+=element->ThicknessAbsMisfit(weight_index);
 	}
 
Index: /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _THICKNESSABSMISFITX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 15396)
@@ -6,9 +6,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
 
 	/*Intermediary*/
@@ -23,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->ThicknessAcrossGradient(process_units,weight_index);
+		J+=element->ThicknessAcrossGradient(weight_index);
 	}
 
Index: /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _THICKNESSACROSSGRADIENT_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 15396)
@@ -6,9 +6,7 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
 
 	/*Intermediary*/
@@ -23,5 +21,5 @@
 	for (i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		J+=element->ThicknessAlongGradient(process_units,weight_index);
+		J+=element->ThicknessAlongGradient(weight_index);
 	}
 
Index: /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h	(revision 15396)
@@ -6,9 +6,8 @@
 #define _THICKNESSALONGGRADIENT_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp	(revision 15396)
@@ -6,5 +6,4 @@
 #include "../../classes/RiftStruct.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
 
Index: /issm/trunk/src/c/modules/TriMeshx/TriMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/TriMeshx/TriMeshx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/TriMeshx/TriMeshx.cpp	(revision 15396)
@@ -6,8 +6,5 @@
 #include "./TriMeshx.h"
 #include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 /*ANSI_DECLARATORS needed to call triangle library: */
 #if defined(_HAVE_TRIANGLE_)
@@ -22,5 +19,5 @@
 /*}}}*/
 
-void TriMeshx(SeqMat<int>** pindex,SeqVec<IssmPDouble>** px,SeqVec<IssmPDouble>** py,SeqMat<int>** psegments,SeqVec<int>** psegmentmarkerlist,DataSet* domain,DataSet* rifts,double area){
+void TriMeshx(int** pindex,IssmPDouble** px,IssmPDouble** py,int** psegments,int** psegmentmarkerlist,int* pnels,int* pnods, int* pnsegs,Contours* domain,Contours* rifts,double area){
 
 #if !defined(_HAVE_TRIANGLE_)
@@ -31,11 +28,9 @@
 
 	/*output: */
-	int         *index             = NULL;
-	SeqMat<int> *index_matrix      = NULL;
-	double      *x                 = NULL;
-	double      *y                 = NULL;
-	int         *segments          = NULL;
-	SeqMat<int> *segments_matrix   = NULL;
-	int         *segmentmarkerlist = NULL;
+	int    *index             = NULL;
+	double *x                 = NULL;
+	double *y                 = NULL;
+	int    *segments          = NULL;
+	int    *segmentmarkerlist = NULL;
 
 	/*intermediary: */
@@ -197,13 +192,12 @@
 
 	/*Output : */
-	index_matrix=new SeqMat<int>(index,out.numberoftriangles,3,1);
-	*pindex=index_matrix;
-
-	segments_matrix=new SeqMat<int>(segments,out.numberofsegments,3,1);
-	*psegments=segments_matrix;
-
-	*px=new SeqVec<IssmPDouble>(x,out.numberofpoints);
-	*py=new SeqVec<IssmPDouble>(y,out.numberofpoints);
-	*psegmentmarkerlist=new SeqVec<int>(segmentmarkerlist,out.numberofsegments);
+	*pindex=index;
+	*px=x;
+	*py=y;
+	*psegments=segments;
+	*psegmentmarkerlist=segmentmarkerlist;
+	*pnels=out.numberoftriangles;
+	*pnods=out.numberofpoints;
+	*pnsegs=out.numberofsegments;
 #endif
 }
Index: /issm/trunk/src/c/modules/TriMeshx/TriMeshx.h
===================================================================
--- /issm/trunk/src/c/modules/TriMeshx/TriMeshx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/TriMeshx/TriMeshx.h	(revision 15396)
@@ -7,9 +7,7 @@
 
 #include <string.h>
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
-void TriMeshx(SeqMat<int>** pindex,SeqVec<IssmPDouble>** px,SeqVec<IssmPDouble>** py,SeqMat<int>** psegments,SeqVec<int>** psegmentmarkerlist,DataSet* domain,DataSet* rifts,double area);
-
+void TriMeshx(int** pindex,IssmPDouble** px,IssmPDouble** py,int** psegments,int** psegmentmarkerlist,int* pnels,int* pnods, int* pnseg,Contours* domain,Contours* rifts,double area);
 #endif  /* _TRIMESHX_H */
Index: /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.cpp
===================================================================
--- /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 15396)
@@ -5,8 +5,6 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../classes/objects/objects.h"
-#include "../modules.h"
+#include "../../bamg/bamgobjects.h"
 
 using namespace bamg;
Index: /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.h
===================================================================
--- /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _TRIASEARCHX_H
 
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 15396)
@@ -6,7 +6,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector<IssmDouble>* yg){
Index: /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _UPDATEDYNAMICCONSTRAINTSXX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector<IssmDouble>* yg);
Index: /issm/trunk/src/c/modules/VecMergex/VecMergex.cpp
===================================================================
--- /issm/trunk/src/c/modules/VecMergex/VecMergex.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/VecMergex/VecMergex.cpp	(revision 15396)
@@ -6,7 +6,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 void VecMergex(Vector<IssmDouble>* ug, Vector<IssmDouble>* uf, Nodes* nodes, Parameters* parameters, int SetEnum){
 
Index: /issm/trunk/src/c/modules/VecMergex/VecMergex.h
===================================================================
--- /issm/trunk/src/c/modules/VecMergex/VecMergex.h	(revision 15395)
+++ /issm/trunk/src/c/modules/VecMergex/VecMergex.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _VECMERGEX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/VertexCoordinatesx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/VertexCoordinatesx/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/modules/VertexCoordinatesx/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,8 @@
+# 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/VertexCoordinatesx/VertexCoordinatesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.cpp	(revision 15396)
+++ /issm/trunk/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.cpp	(revision 15396)
@@ -0,0 +1,61 @@
+/*!\file VertexCoordinatesx
+ * \brief: compute a vector x,y and z of vertex coordinates by 
+ * marching through all our vertices. 
+ */
+
+#include "./VertexCoordinatesx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void VertexCoordinatesx( IssmDouble** px, IssmDouble** py, IssmDouble** pz, Vertices* vertices) {
+
+	/*output: */
+	IssmDouble* x=NULL;
+	IssmDouble* y=NULL;
+	IssmDouble* z=NULL;
+
+	Vector<IssmDouble>* vx=NULL;
+	Vector<IssmDouble>* vy=NULL;
+	Vector<IssmDouble>* vz=NULL;
+
+	/*intermediary: */
+	int  numberofvertices;
+	int  i;
+
+	/*figure out how many vertices we have: */
+	numberofvertices=vertices->NumberOfVertices();
+
+	vx=new Vector<IssmDouble>(numberofvertices);
+	vy=new Vector<IssmDouble>(numberofvertices);
+	vz=new Vector<IssmDouble>(numberofvertices);
+
+	/*march through our vertices: */
+	for(i=0;i<vertices->Size();i++){
+		Vertex* vertex=(Vertex*)vertices->GetObjectByOffset(i);
+		vertex->VertexCoordinates(vx,vy,vz);
+	}
+
+	/*Assemble*/
+	vx->Assemble();
+	vy->Assemble();
+	vz->Assemble();
+
+	/*serialize: */
+	x=vx->ToMPISerial();
+	y=vy->ToMPISerial();
+	z=vz->ToMPISerial();
+
+	/*Free ressources: */
+	delete vx;
+	delete vy;
+	delete vz;
+
+	/*output: */
+	if (px)*px=x;
+	else xDelete<IssmDouble>(x);
+	if (py)*py=y;
+	else xDelete<IssmDouble>(y);
+	if (pz)*pz=z;
+	else xDelete<IssmDouble>(z);
+}
Index: /issm/trunk/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.h
===================================================================
--- /issm/trunk/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.h	(revision 15396)
+++ /issm/trunk/src/c/modules/VertexCoordinatesx/VertexCoordinatesx.h	(revision 15396)
@@ -0,0 +1,12 @@
+/*!\file:  VertexCoordinatesx.h
+ */ 
+
+#ifndef _VERTEX_COORDINATESX_H
+#define _VERTEX_COORDINATESX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void VertexCoordinatesx( IssmDouble** px, IssmDouble** py, IssmDouble** pz, Vertices* vertices);
+
+#endif  /* _VERTEX_COORDINATESX_H */
Index: /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.cpp
===================================================================
--- /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.cpp	(revision 15395)
+++ /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.cpp	(revision 15396)
@@ -5,7 +5,5 @@
 
 #include "../../shared/shared.h"
-#include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
 
 void VerticesDofx( Vertices* vertices, Parameters* parameters) {
Index: /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.h
===================================================================
--- /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 15395)
+++ /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 15396)
@@ -6,6 +6,5 @@
 #define _VERTICESDOFX_H
 
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/modules.h
===================================================================
--- /issm/trunk/src/c/modules/modules.h	(revision 15395)
+++ /issm/trunk/src/c/modules/modules.h	(revision 15396)
@@ -25,9 +25,9 @@
 #include "./DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
 #include "./ElementConnectivityx/ElementConnectivityx.h"
-#include "./EnumToStringx/EnumToStringx.h"
-#include "./StringToEnumx/StringToEnumx.h"
+#include "./EdgeDetectionx/EdgeDetectionx.h"
 #include "./GetSolutionFromInputsx/GetSolutionFromInputsx.h"
 #include "./GetVectorFromInputsx/GetVectorFromInputsx.h"
 #include "./GetVectorFromControlInputsx/GetVectorFromControlInputsx.h"
+#include "./GiaDeflectionCorex/GiaDeflectionCorex.h"
 #include "./SetControlInputsFromVectorx/SetControlInputsFromVectorx.h"
 #include "./Gradjx/Gradjx.h"
@@ -35,5 +35,4 @@
 #include "./HoleFillerx/HoleFillerx.h"
 #include "./InputControlUpdatex/InputControlUpdatex.h"
-#include "./InputConvergencex/InputConvergencex.h"
 #include "./InputDuplicatex/InputDuplicatex.h"
 #include "./InputScalex/InputScalex.h"
@@ -55,6 +54,4 @@
 #include "./KMLMeshWritex/KMLMeshWritex.h"
 #include "./KMLOverlayx/KMLOverlayx.h"
-#include "./Xy2llx/Xy2llx.h"
-#include "./Ll2xyx/Ll2xyx.h"
 #include "./Exp2Kmlx/Exp2Kmlx.h"
 #include "./Kml2Expx/Kml2Expx.h"
@@ -69,5 +66,5 @@
 #include "./SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h"
 #include "./ModelProcessorx/ModelProcessorx.h"
-#include "./ParsePetscOptionsx/ParsePetscOptionsx.h"
+#include "./ParseToolkitsOptionsx/ParseToolkitsOptionsx.h"
 #include "./NodalValuex/NodalValuex.h"
 #include "./NodeConnectivityx/NodeConnectivityx.h"
@@ -100,4 +97,5 @@
 #include "./UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h"
 #include "./VerticesDofx/VerticesDofx.h"
+#include "./VertexCoordinatesx/VertexCoordinatesx.h"
 #include "./VecMergex/VecMergex.h"
 #endif
Index: /issm/trunk/src/c/shared/Bamg/BigPrimeNumber.cpp
===================================================================
--- /issm/trunk/src/c/shared/Bamg/BigPrimeNumber.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Bamg/BigPrimeNumber.cpp	(revision 15396)
@@ -1,3 +1,4 @@
-#include "./BigPrimeNumber.h"
+#include "./Abs.h"
+#include "./extrema.h"
 
 namespace bamg {
Index: /issm/trunk/src/c/shared/Bamg/BigPrimeNumber.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/BigPrimeNumber.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Bamg/BigPrimeNumber.h	(revision 15396)
@@ -1,7 +1,4 @@
 #ifndef _BIGPRIMENUMBER_H_
 #define _BIGPRIMENUMBER_H_
-
-#include "./Abs.h"
-#include "./extrema.h"
 
 namespace bamg {
Index: /issm/trunk/src/c/shared/Bamg/HeapSort.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/HeapSort.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Bamg/HeapSort.h	(revision 15396)
@@ -3,42 +3,64 @@
 
 /*Sort a list of size n*/
-template<class T> inline void  HeapSort(T *c,long n){
-	int l,j,r,i;
+template<class T> inline void  HeapSort(T *c,long n){ /*{{{*/
+
+	/*Intermediaries*/
+	int i,j,l,r;
 	T   crit;
-	c--;                    //the array must starts at 1 and not 0 
-	if(n<=1) return;        //return if size <=1
-	l=n/2+1;                //initialize l and r
+
+	/*return if size <=1*/
+	if(n<=1) return;
+
+	/*Initialize variables*/
+	l=n/2+1; 
 	r=n;
+	c--; //the array must starts at 1 and not 0 
+
+	/*Sorting algorithm*/
 	for(;;){
 		if(l<=1){
-			crit  =c[r];
-			c[r--]=c[1];
-			if (r==1){c[1]=crit; return;}
+			crit   = c[r];
+			c[r--] = c[1];
+			if(r==1){
+				c[1]=crit; 
+				return;
+			}
 		}
-		else  crit = c[--l]; 
+		else{
+			crit = c[--l]; 
+		}
 		j=l;
 		for(;;){
-			i=j;
-			j=2*j;
-			if  (j>r) {c[i]=crit;break;}
+			i = j;
+			j = 2*j;
+			if  (j>r){c[i]=crit;break;}
 			if ((j<r) && (c[j] < c[j+1])) j++;//c[j+1]> c[j] -> take j+1 instead of j (larger value)
-			if (crit < c[j]) c[i]=c[j];       //c[j]  > crit -> stock this large value in i(<j)
-			else{c[i]=crit;break;}            //c[j]  < crit -> stock crit in i (<j)
+			if (crit < c[j]) c[i]=c[j];       //c[j]  > crit -> put this large value in i(<j)
+			else{c[i]=crit;break;}            //c[j]  < crit -> put crit in i (<j)
 		}
 	}
 }
+/*}}}*/
 
 /*Sort a list of size n and returns ordering*/
-template<class T> inline void  HeapSort(int** porder,T* c,int n){
-	int  l,j,r,i;
+template<class T> inline void  HeapSort(int** porder,T* c,int n){ /*{{{*/
+
+	/*Intermediaries*/
+	int  i,j,l,r;
 	T    crit;
 	int  pos;
-	int* order = new int[n];
+	int* order = NULL;
+
+	/*return if size <=1*/
+	if(n<=1) return;
+
+	/*Initialize variables*/
+	l=n/2+1; 
+	r=n;
+	c--; //the array must starts at 1 and not 0 
+	order = new int[n];
 	for(i=0;i<n;i++) order[i]=i+1;
-	c--;                    //the array must starts at 1 and not 0 
-	order--;
-	if(n<=1) return;        //return if size <=1
-	l=n/2+1;                //initialize l and r
-	r=n;
+
+	/*Sorting algorithm*/
 	for(;;){
 		if(l<=1){
@@ -63,5 +85,5 @@
 		}
 	}
-}
+}/*}}}*/
 
 #endif
Index: /issm/trunk/src/c/shared/Bamg/OppositeAngle.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/OppositeAngle.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Bamg/OppositeAngle.h	(revision 15396)
@@ -2,10 +2,10 @@
 #define _OPPOSITEANGLE_H_
 
-#include "../../classes/bamg/include.h"
+#include "../Numerics/constants.h"
 
 /*Return the opposite angle modulo 2 Pi*/
 namespace bamg {
-	inline float  OppositeAngle(float  a){return a<0 ? fPi+a:a-fPi;}
-	inline double OppositeAngle(double a){return a<0 ?  Pi+a:a- Pi;}
+	inline float  OppositeAngle(float  a){return a<0 ? PI+a:a-PI;}
+	inline double OppositeAngle(double a){return a<0 ?  PI+a:a- PI;}
 }
 
Index: sm/trunk/src/c/shared/Bamg/det.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/det.h	(revision 15395)
+++ 	(revision )
@@ -1,15 +1,0 @@
-#ifndef _BAMGDET_H_
-#define _BAMGDET_H_
-
-#include "../../classes/bamg/include.h"
-
-namespace bamg {
-
-	Icoor2 inline det(const I2 &a,const I2 & b,const I2 &c){
-		Icoor2 bax = b.x - a.x ,bay = b.y - a.y; 
-		Icoor2 cax = c.x - a.x ,cay = c.y - a.y; 
-		return  bax*cay - bay*cax;
-	}
-
-}
-#endif
Index: /issm/trunk/src/c/shared/Bamg/shared.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/shared.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Bamg/shared.h	(revision 15396)
@@ -9,5 +9,4 @@
 #include "BigPrimeNumber.h"
 #include "BinaryRand.h"
-#include "det.h"
 #include "Exchange.h"
 #include "extrema.h"
Index: /issm/trunk/src/c/shared/Elements/Arrhenius.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/Arrhenius.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Elements/Arrhenius.cpp	(revision 15396)
@@ -3,6 +3,7 @@
  */
 
-#include "./elements.h"
 #include <math.h>
+#include "../Numerics/types.h"
+#include "../Exceptions/exceptions.h"
 
 IssmDouble Arrhenius(IssmDouble temperature,IssmDouble depth,IssmDouble n){
Index: /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 15396)
@@ -5,4 +5,5 @@
 
 #include "./elements.h"
+#include "../Numerics/numerics.h"
 
 void ComputeDelta18oTemperaturePrecipitation(IssmDouble Delta18oSurfacePresent, IssmDouble Delta18oSurfaceLgm, IssmDouble Delta18oSurfaceTime,
Index: sm/trunk/src/c/shared/Elements/CoordinateSystemTransform.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/CoordinateSystemTransform.cpp	(revision 15395)
+++ 	(revision )
@@ -1,75 +1,0 @@
-/*!\file:  GetGlobalDofList.cpp
- * \brief create transform matrix for different coordinate systems
- */ 
-#include "./elements.h"
-#include <math.h>
-
-void CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array){
-
-	int     i,counter;
-	int     numdofs           = 0;
-	IssmDouble  norm;
-	IssmDouble *transform         = NULL;
-	IssmDouble *values            = NULL;
-	IssmDouble  coord_system[3][3];
-
-	/*Some checks in debugging mode*/
-	_assert_(numnodes && nodes);
-
-	/*Get total number of dofs*/
-	for(i=0;i<numnodes;i++){
-		switch(cs_array[i]){
-			case XYEnum:   numdofs+=2; break;
-			case XYZPEnum: numdofs+=4; break;
-			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
-		}
-	}
-
-	/*Allocate and initialize transform matrix*/
-	transform=xNew<IssmDouble>(numdofs*numdofs);
-	for(i=0;i<numdofs*numdofs;i++) transform[i]=0.0;
-
-	/*Create transform matrix for all nodes (x,y for 2d and x,y,z for 3d). It is a block matrix
-	 *for 3 nodes:
-
-	 *     | T1 0  0 |
-	 * Q = | 0  T2 0 |
-	 *     | 0  0  T3|
-	 *
-	 * Where T1 is the transform matrix for node 1. It is a simple copy of the coordinate system
-	 * associated to this node*/
-	counter=0;
-	for(i=0;i<numnodes;i++){
-		nodes[i]->GetCoordinateSystem(&coord_system[0][0]);
-		switch(cs_array[i]){
-			case XYEnum:
-				/*We remove the z component, we need to renormalize x and y: x=[x1 x2 0] y=[-x2 x1 0]*/
-				norm = sqrt( coord_system[0][0]*coord_system[0][0] + coord_system[1][0]*coord_system[1][0]); _assert_(norm>1.e-4);
-				transform[(numdofs)*(counter+0) + counter+0] =   coord_system[0][0]/norm;
-				transform[(numdofs)*(counter+0) + counter+1] = - coord_system[1][0]/norm;
-				transform[(numdofs)*(counter+1) + counter+0] =   coord_system[1][0]/norm;
-				transform[(numdofs)*(counter+1) + counter+1] =   coord_system[0][0]/norm;
-				counter+=2;
-				break;
-			case XYZPEnum:
-				/*Only the first 3 coordinates are changed (x,y,z), leave the others (P) unchanged*/
-				transform[(numdofs)*(counter+0) + counter+0] = coord_system[0][0];
-				transform[(numdofs)*(counter+0) + counter+1] = coord_system[0][1];
-				transform[(numdofs)*(counter+0) + counter+2] = coord_system[0][2];
-				transform[(numdofs)*(counter+1) + counter+0] = coord_system[1][0];
-				transform[(numdofs)*(counter+1) + counter+1] = coord_system[1][1];
-				transform[(numdofs)*(counter+1) + counter+2] = coord_system[1][2];
-				transform[(numdofs)*(counter+2) + counter+0] = coord_system[2][0];
-				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;
-				break;
-			default:
-				_error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
-		}
-	}
-
-	/*Assign output pointer*/
-	*ptransform=transform;
-}
Index: sm/trunk/src/c/shared/Elements/GetGlobalDofList.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/GetGlobalDofList.cpp	(revision 15395)
+++ 	(revision )
@@ -1,41 +1,0 @@
-/*!\file:  GetGlobalDofList.cpp
- * \brief create new element matrix
- */ 
-#include "./elements.h"
-
-int* GetGlobalDofList(Node** nodes,int numnodes,int setenum,int approximation){
-
-	int  i,numdof,count;
-	int* ndof_list=NULL;
-	int *doflist = NULL;
-
-	if(numnodes){
-
-		/*Allocate:*/
-		ndof_list=xNew<int>(numnodes);
-
-		/*First, figure out size of doflist: */
-		numdof=0;
-		for(i=0;i<numnodes;i++){
-			ndof_list[i]=nodes[i]->GetNumberOfDofs(approximation,setenum);
-			numdof+=ndof_list[i];
-		}
-
-		if(numdof){
-			/*Allocate: */
-			doflist=xNew<int>(numdof);
-
-			/*Populate: */
-			count=0;
-			for(i=0;i<numnodes;i++){
-				nodes[i]->GetDofList(&doflist[count],approximation,setenum);
-				count+=ndof_list[i];
-			}
-		}
-		else doflist=NULL;
-	}
-	/*Free ressources:*/
-	xDelete<int>(ndof_list);
-
-	return doflist;
-}
Index: sm/trunk/src/c/shared/Elements/GetLocalDofList.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/GetLocalDofList.cpp	(revision 15395)
+++ 	(revision )
@@ -1,61 +1,0 @@
-/*!\file:  GetLocalDofList.cpp
- * \brief create new element matrix
- */ 
-#include "./elements.h"
-
-int* GetLocalDofList(Node** nodes,int numnodes,int setenum,int approximation){
-
-	int  i,j,count,numdof,numgdof;
-	int* ndof_list=NULL;
-	int* ngdof_list_cumulative=NULL;
-	int *doflist = NULL;
-
-	if(numnodes){
-		/*allocate: */
-		ndof_list=xNew<int>(numnodes);
-		ngdof_list_cumulative=xNew<int>(numnodes);
-
-		/*Get number of dofs per node, and total for this given set*/
-		numdof=0;
-		numgdof=0;
-		for(i=0;i<numnodes;i++){
-
-			/*Cumulative list= number of dofs before node i*/
-			ngdof_list_cumulative[i]=numgdof;
-
-			/*Number of dofs for node i for given set and for the g set*/
-			ndof_list[i]=nodes[i]->GetNumberOfDofs(approximation,setenum);
-			numgdof    +=nodes[i]->GetNumberOfDofs(approximation,GsetEnum);
-			numdof     +=ndof_list[i];
-		}
-
-		if(numdof){
-			/*Allocate: */
-			doflist=xNew<int>(numdof);
-
-			/*Populate: */
-			count=0;
-			for(i=0;i<numnodes;i++){
-				nodes[i]->GetLocalDofList(&doflist[count],approximation,setenum);
-				count+=ndof_list[i];
-			}
-
-			/*We now have something like: [0 1 0 2 1 2]. Offset by gsize, to get something like: [0 1 2 4 6 7]:*/
-			count=0;
-			for(i=0;i<numnodes;i++){
-				for(j=0;j<ndof_list[i];j++){
-					doflist[count+j]+=ngdof_list_cumulative[i];
-				}
-				count+=ndof_list[i];
-			}
-		}
-		else doflist=NULL;
-	}
-
-	/*Free ressources:*/
-	xDelete<int>(ndof_list);
-	xDelete<int>(ngdof_list_cumulative);
-
-	/*CLean-up and return*/
-	return doflist;
-}
Index: sm/trunk/src/c/shared/Elements/GetNumberOfDofs.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/GetNumberOfDofs.cpp	(revision 15395)
+++ 	(revision )
@@ -1,16 +1,0 @@
-/*!\file:  GetNumberOfDofs.cpp
- * \brief create new element matrix
- */ 
-#include "./elements.h"
-
-int GetNumberOfDofs(Node** nodes,int numnodes,int setenum,int approximation){
-
-	/*output: */
-	int numberofdofs=0;
-
-	for(int i=0;i<numnodes;i++){
-		numberofdofs+=nodes[i]->GetNumberOfDofs(approximation,setenum);
-	}
-
-	return numberofdofs;
-}
Index: sm/trunk/src/c/shared/Elements/GetVerticesCoordinates.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/GetVerticesCoordinates.cpp	(revision 15395)
+++ 	(revision )
@@ -1,17 +1,0 @@
-/*!\file:  GetVerticesCoordinates.cpp
- * \brief get node coordinates
- */ 
-
-#include "./elements.h"
-
-void GetVerticesCoordinates(IssmDouble* xyz,  Node** nodes, int numvertices){
-
-	/*In debugging mode, check that nodes is not a NULL pointer*/
-	_assert_(nodes);
-
-	for(int i=0;i<numvertices;i++) {
-		xyz[i*3+0]=nodes[i]->GetX();
-		xyz[i*3+1]=nodes[i]->GetY();
-		xyz[i*3+2]=nodes[i]->GetZ();
-	}
-}
Index: /issm/trunk/src/c/shared/Elements/Paterson.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/Paterson.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Elements/Paterson.cpp	(revision 15396)
@@ -7,5 +7,5 @@
 #include <math.h>
 
-#include "../../include/include.h"
+#include "../Numerics/types.h"
 
 IssmDouble Paterson(IssmDouble temperature){
Index: /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 15396)
@@ -4,10 +4,10 @@
 
 #include "./elements.h"
-
-IssmDouble PddSurfaceMassBlance(IssmDouble* monthlytemperatures, IssmDouble* monthlyprec, IssmDouble* pdds, IssmDouble* pds, IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s, IssmDouble rho_ice, IssmDouble rho_water){
+#include "../Numerics/numerics.h"
+
+IssmDouble PddSurfaceMassBlance(IssmDouble* monthlytemperatures, IssmDouble* monthlyprec, IssmDouble* pdds, IssmDouble* pds, IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s, IssmDouble rho_ice, IssmDouble rho_water, IssmDouble desfac, IssmDouble s0p){ 
 
   // output:
   IssmDouble B;    // surface mass balance, melt+accumulation
-
   int    iqj,imonth;
 
@@ -20,7 +20,7 @@
   IssmDouble sconv; //rhow_rain/rhoi / 12 months
 
-  IssmDouble lapser=6.5/1000., sealev=0.;    // lapse rate. degrees per meter. 7.5 lev's 99 paper, 9 Marshall 99 paper
-  IssmDouble desfac = 0.5;                 // desert elevation factor
-  IssmDouble s0p=0.;         // should be set to elevation from precip source
+  IssmDouble lapser=6.5, sealev=0.;    // lapse rate. degrees per meter. 7.5 lev's 99 paper, 9 Marshall 99 paper
+  // IssmDouble desfac = 0.5;                 // desert elevation factor
+  // IssmDouble s0p=0.;         // should be set to elevation from precip source
   IssmDouble s0t=0.;         // should be set to elevation from temperature source
   IssmDouble st;             // elevation between altitude of the temp record and current altitude
@@ -96,4 +96,5 @@
       // gaussian=T_m, so ndd=-(Tsurf-pdd)
       if (iqj>5 &&  iqj<9){ Tsum=Tsum+tstar;} 
+
       if (tstar >= siglim) {pdd = pdd + tstar*deltm;}
       else if (tstar> -siglim){
@@ -103,6 +104,6 @@
       else{frzndd = frzndd - tstar*deltm; }
   } // end of seasonal loop 
-
   //******************************************************************
+
     saccu = qm;
     prect = qmp;     // total precipitation during 1 year taking into account des. ef.
Index: /issm/trunk/src/c/shared/Elements/PrintArrays.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/PrintArrays.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Elements/PrintArrays.cpp	(revision 15396)
@@ -1,50 +1,53 @@
 
 #include "./elements.h"
-#include "../../include/macros.h"
+#include "../io/Print/Print.h"
 using namespace std;
 
 void printarray(IssmPDouble* array,int lines,int cols){
-	_printLine_("");
+	_printf_("\n");
 	for(int i=0;i<lines;i++){  
-		_printString_("   [ ");
-		for(int j=0;j<cols;j++) _printString_( " " << setw(11) << setprecision (5) << array[i*cols+j]);
-		_printLine_(" ]");
+		_printf_("   [ ");
+		for(int j=0;j<cols;j++) _printf_( " " << setw(11) << setprecision (5) << array[i*cols+j]);
+		_printf_(" ]\n");
 	}  
-	_printLine_("");
+	_printf_("\n");
 }
 void printsparsity(IssmPDouble* array,int lines,int cols){
 	int count;
-	_printLine_("");
+	_printf_("\n");
 	for(int i=0;i<lines;i++){  
-		_printString_("   [ ");
+		_printf_("   [ ");
 		count = 0;
 		for(int j=0;j<cols;j++){
 			if(array[i*cols+j]!=0.0){
-				_printString_( " X"); count++;
+				_printf_( " X"); count++;
 			}
 			else
-			 _printString_( " .");
+			 _printf_( " .");
 		}
-		_printLine_(" ] "<<i<<" => "<<count);
+		_printf_(" ] "<<i<<" => "<<count << "\n");
 	}  
-	_printLine_("");
+	_printf_("\n");
 }
 void printarray(int* array,int lines,int cols){
-	_printLine_("");
+	_printf_("\n");
 	for(int i=0;i<lines;i++){  
-		_printString_("   [ ");
-		for(int j=0;j<cols;j++) _printString_( " " << setw(11) << setprecision (5) << array[i*cols+j]);
-		_printLine_(" ]");
+		_printf_("   [ ");
+		for(int j=0;j<cols;j++) _printf_( " " << setw(11) << setprecision (5) << array[i*cols+j]);
+		_printf_(" ]\n");
 	}  
-	_printLine_("");
+	_printf_("\n");
 }
 void printarray(bool* array,int lines,int cols){
-	_printLine_("");
+	_printf_("\n");
 	for(int i=0;i<lines;i++){  
-		_printString_("   [ ");
-		for(int j=0;j<cols;j++) _printString_( " " << array[i*cols+j]?1:0);
-		_printLine_(" ]");
+		_printf_("   [ ");
+		for(int j=0;j<cols;j++){
+			if(array[i*cols+j]) _printf_( " 1");
+			else _printf_( " 0");
+		}
+		_printf_(" ]\n");
 	}  
-	_printLine_("");
+	_printf_("\n");
 }
 void printbinary(int n){
@@ -52,7 +55,7 @@
 	while (i>0) {
 		if (n&i)
-		 _printString_("1");
+		 _printf_("1");
 		else
-		 _printString_("0");
+		 _printf_("0");
 		i>>=1;
 	}
Index: sm/trunk/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp	(revision 15395)
+++ 	(revision )
@@ -1,53 +1,0 @@
-/*!\file:  TransformInvStiffnessMatrixCoord.cpp
- * \brief transform stiffness matrix inverse coordinate system
- */ 
-#include "./elements.h"
-
-void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum){
-
-	int* cs_array=NULL;
-
-	/*All nodes have the same Coordinate System*/
-	cs_array=xNew<int>(numnodes);
-	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
-
-	/*Call core*/
-	TransformInvStiffnessMatrixCoord(Ke,nodes,numnodes,cs_array);
-
-	/*Clean-up*/
-	xDelete<int>(cs_array);
-}
-
-void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array){
-
-	int     i,j;
-	int     numdofs   = 0;
-	IssmDouble *transform = NULL;
-	IssmDouble *values    = NULL;
-
-	/*Get total number of dofs*/
-	for(i=0;i<numnodes;i++){
-		switch(cs_array[i]){
-			case XYEnum:   numdofs+=2; break;
-			case XYZPEnum: numdofs+=4; break;
-			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
-		}
-	}
-
-	/*Copy current stiffness matrix*/
-	values=xNew<IssmDouble>(Ke->nrows*Ke->ncols);
-	for(i=0;i<Ke->nrows;i++) for(j=0;j<Ke->ncols;j++) values[i*Ke->ncols+j]=Ke->values[i*Ke->ncols+j];
-
-	/*Get Coordinate Systems transform matrix*/
-	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
-
-	/*Transform matrix: R*Ke*R^T */
-	TripleMultiply(transform,numdofs,numdofs,0,
-				values,Ke->nrows,Ke->ncols,0,
-				transform,numdofs,numdofs,1,
-				&Ke->values[0],0);
-
-	/*Free Matrix*/
-	xDelete<IssmDouble>(transform);
-	xDelete<IssmDouble>(values);
-}
Index: sm/trunk/src/c/shared/Elements/TransformLoadVectorCoord.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 15395)
+++ 	(revision )
@@ -1,51 +1,0 @@
-/*!\file:  TransformLoadVectorCoord.cpp
- * \brief transform load vector coordinate system
- */ 
-#include "./elements.h"
-
-void TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int cs_enum){
-	int* cs_array=NULL;
-
-	/*All nodes have the same Coordinate System*/
-	cs_array=xNew<int>(numnodes);
-	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
-
-	/*Call core*/
-	TransformLoadVectorCoord(pe,nodes,numnodes,cs_array);
-
-	/*Clean-up*/
-	xDelete<int>(cs_array);
-}
-
-void TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array){
-
-	int     i;
-	int     numdofs   = 0;
-	IssmDouble *transform = NULL;
-	IssmDouble *values    = NULL;
-
-	/*Get total number of dofs*/
-	for(i=0;i<numnodes;i++){
-		switch(cs_array[i]){
-			case XYEnum:   numdofs+=2; break;
-			case XYZPEnum: numdofs+=4; break;
-			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
-		}
-	}
-
-	/*Copy current load vector*/
-	values=xNew<IssmDouble>(pe->nrows);
-	for(i=0;i<pe->nrows;i++) values[i]=pe->values[i];
-
-	/*Get Coordinate Systems transform matrix*/
-	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
-
-	/*Transform matrix: R^T*pe */
-	MatrixMultiply(transform,numdofs,numdofs,1,
-				values,pe->nrows,1,0,
-				&pe->values[0],0);
-
-	/*Free Matrices*/
-	xDelete<IssmDouble>(transform);
-	xDelete<IssmDouble>(values);
-}
Index: sm/trunk/src/c/shared/Elements/TransformSolutionCoord.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 15395)
+++ 	(revision )
@@ -1,52 +1,0 @@
-/*!\file:  TransformSolutionCoord.cpp
- * \brief transform solution vector coordinate system
- */ 
-#include "./elements.h"
-
-void TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int cs_enum){
-
-	int* cs_array=NULL;
-
-	/*All nodes have the same Coordinate System*/
-	cs_array=xNew<int>(numnodes);
-	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
-
-	/*Call core*/
-	TransformSolutionCoord(solution,nodes,numnodes,cs_array);
-
-	/*Clean-up*/
-	xDelete<int>(cs_array);
-}
-
-void TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int* cs_array){
-
-	int     i;
-	int     numdofs   = 0;
-	IssmDouble *transform = NULL;
-	IssmDouble *values    = NULL;
-
-	/*Get total number of dofs*/
-	for(i=0;i<numnodes;i++){
-		switch(cs_array[i]){
-			case XYEnum:   numdofs+=2; break;
-			case XYZPEnum: numdofs+=4; break;
-			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
-		}
-	}
-
-	/*Copy current solution vector*/
-	values=xNew<IssmDouble>(numdofs);
-	for(i=0;i<numdofs;i++) values[i]=solution[i];
-
-	/*Get Coordinate Systems transform matrix*/
-	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
-
-	/*Transform matrix: R*U */
-	MatrixMultiply(transform,numdofs,numdofs,0,
-				values,numdofs,1,0,
-				&solution[0],0);
-
-	/*Free Matrices*/
-	xDelete<IssmDouble>(transform);
-	xDelete<IssmDouble>(values);
-}
Index: sm/trunk/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp	(revision 15395)
+++ 	(revision )
@@ -1,53 +1,0 @@
-/*!\file:  TransformStiffnessMatrixCoord.cpp
- * \brief transform stiffness matrix coordinate system
- */ 
-#include "./elements.h"
-
-void TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum){
-
-	int* cs_array=NULL;
-
-	/*All nodes have the same Coordinate System*/
-	cs_array=xNew<int>(numnodes);
-	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
-
-	/*Call core*/
-	TransformStiffnessMatrixCoord(Ke,nodes,numnodes,cs_array);
-
-	/*Clean-up*/
-	xDelete<int>(cs_array);
-}
-
-void TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array){
-
-	int     i,j;
-	int     numdofs   = 0;
-	IssmDouble *transform = NULL;
-	IssmDouble *values    = NULL;
-
-	/*Get total number of dofs*/
-	for(i=0;i<numnodes;i++){
-		switch(cs_array[i]){
-			case XYEnum:   numdofs+=2; break;
-			case XYZPEnum: numdofs+=4; break;
-			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
-		}
-	}
-
-	/*Copy current stiffness matrix*/
-	values=xNew<IssmDouble>(Ke->nrows*Ke->ncols);
-	for(i=0;i<Ke->nrows;i++) for(j=0;j<Ke->ncols;j++) values[i*Ke->ncols+j]=Ke->values[i*Ke->ncols+j];
-
-	/*Get Coordinate Systems transform matrix*/
-	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
-
-	/*Transform matrix: R^T*Ke*R */
-	TripleMultiply(transform,numdofs,numdofs,1,
-				values,Ke->nrows,Ke->ncols,0,
-				transform,numdofs,numdofs,0,
-				&Ke->values[0],0);
-
-	/*Free Matrix*/
-	xDelete<IssmDouble>(transform);
-	xDelete<IssmDouble>(values);
-}
Index: /issm/trunk/src/c/shared/Elements/elements.h
===================================================================
--- /issm/trunk/src/c/shared/Elements/elements.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Elements/elements.h	(revision 15396)
@@ -6,13 +6,11 @@
 #define _SHARED_ELEMENTS_H_
 
-#include "../../classes/objects/objects.h"
-#include "../../Container/Container.h"
-class ElementMatrix;
-class ElementVector;
+#include "../Numerics/types.h"
 
 IssmDouble Paterson(IssmDouble temperature);
 IssmDouble Arrhenius(IssmDouble temperature,IssmDouble depth,IssmDouble n);
 IssmDouble PddSurfaceMassBlance(IssmDouble* monthlytemperatures,  IssmDouble* monthlyprec, IssmDouble* pdds, IssmDouble* pds, 
-				IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s, IssmDouble rho_ice, IssmDouble rho_water);
+				IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s,
+				IssmDouble rho_ice, IssmDouble rho_water, IssmDouble desfac, IssmDouble s0p);
 void ComputeDelta18oTemperaturePrecipitation(IssmDouble Delta18oSurfacePresent, IssmDouble Delta18oSurfaceLgm, IssmDouble Delta18oSurfaceTime,
 				     IssmDouble Delta18oPresent, IssmDouble Delta18oLgm, IssmDouble Delta18oTime, 
@@ -20,20 +18,4 @@
 				     IssmDouble* TemperaturesLgm, IssmDouble* TemperaturesPresentday, 
 					     IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout);
-void   GetVerticesCoordinates(IssmDouble* xyz,  Node** nodes, int numvertices);
-int    GetNumberOfDofs( Node** nodes,int numnodes,int setenum,int approximation_enum);
-int*   GetLocalDofList( Node** nodes,int numnodes,int setenum,int approximation_enum);
-int*   GetGlobalDofList(Node** nodes,int numnodes,int setenum,int approximation_enum);
-
-#ifdef _HAVE_DIAGNOSTIC_
-void   CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array);
-void   TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
-void   TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
-void   TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
-void   TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
-void   TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int cs_enum);
-void   TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array);
-void   TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int cs_enum);
-void   TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int* cs_array);
-#endif
 
 /*Print arrays*/
Index: /issm/trunk/src/c/shared/Enum/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Enum/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/shared/Enum/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,5 @@
+# Subdirectories {{{
+# }}}
+# Include Directory {{{
+include_directories(AFTER $ENV{ISSM_DIR}/src/c/EnumDefinitions)
+# }}}
Index: /issm/trunk/src/c/shared/Enum/Enum.h
===================================================================
--- /issm/trunk/src/c/shared/Enum/Enum.h	(revision 15396)
+++ /issm/trunk/src/c/shared/Enum/Enum.h	(revision 15396)
@@ -0,0 +1,10 @@
+
+#ifndef _ISSM_ENUM_
+#define _ISSM_ENUM_
+
+#include "./EnumDefinitions.h"
+const char* EnumToStringx(int enum_in);
+void        EnumToStringx(char** string,int enum_in);
+int         StringToEnumx(const char* string_in);
+
+#endif
Index: /issm/trunk/src/c/shared/Enum/EnumDefinitions.h
===================================================================
--- /issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 15396)
+++ /issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 15396)
@@ -0,0 +1,613 @@
+/*
+ * \file EnumDefinitions.h:
+ * \brief: enum functions for our objects
+ */
+
+#ifndef _ENUM_DEFINITIONS_
+#define _ENUM_DEFINITIONS_
+
+enum definitions{
+	/*Model fields {{{*/
+	AutodiffIsautodiffEnum, 
+	AutodiffNumDependentsEnum,
+	AutodiffNumDependentObjectsEnum,
+	AutodiffDependentObjectNamesEnum,
+	AutodiffDependentObjectTypesEnum,
+	AutodiffDependentObjectIndicesEnum,
+	AutodiffDependentObjectsEnum,
+	AutodiffNumIndependentsEnum,
+	AutodiffNumIndependentObjectsEnum,
+	AutodiffIndependentObjectNamesEnum,
+	AutodiffIndependentObjectTypesEnum,
+	AutodiffIndependentObjectsEnum,
+	AutodiffJacobianEnum,
+	AutodiffXpEnum,
+	AutodiffDriverEnum,
+	AutodiffFosForwardIndexEnum,
+	AutodiffFovForwardIndicesEnum,
+	AutodiffFosReverseIndexEnum,
+	AutodiffMassFluxSegmentsPresentEnum,
+	AutodiffKeepEnum,
+	BalancethicknessSpcthicknessEnum,
+	BalancethicknessStabilizationEnum,
+	BalancethicknessThickeningRateEnum,
+	BasalforcingsGeothermalfluxEnum,
+	BasalforcingsMeltingRateCorrectionEnum,
+	BasalforcingsMeltingRateEnum,
+	BathymetryEnum,
+	BedEnum,
+	ConstantsGEnum,
+	ConstantsReferencetemperatureEnum,
+	ConstantsYtsEnum,
+	DependentObjectEnum,
+	DiagnosticAbstolEnum,
+	DiagnosticIcefrontEnum,
+	DiagnosticIsnewtonEnum,
+	DiagnosticMaxiterEnum,
+	DiagnosticNumRequestedOutputsEnum,
+	DiagnosticPenaltyFactorEnum,
+	DiagnosticReferentialEnum,
+	DiagnosticReltolEnum,
+	DiagnosticRequestedOutputsEnum,
+	DiagnosticRestolEnum,
+	DiagnosticRiftPenaltyLockEnum,
+	DiagnosticRiftPenaltyThresholdEnum,
+	DiagnosticShelfDampeningEnum,
+	DiagnosticSpcvxEnum,
+	DiagnosticSpcvyEnum,
+	DiagnosticSpcvzEnum,
+	DiagnosticStokesreconditioningEnum,
+	DiagnosticVertexPairingEnum,
+	DiagnosticViscosityOvershootEnum,
+	LoadingforceXEnum,
+	LoadingforceYEnum,
+	LoadingforceZEnum,
+	FlowequationBordermacayealEnum,
+	FlowequationBorderpattynEnum,
+	FlowequationBorderstokesEnum,
+	FlowequationElementEquationEnum,
+	FlowequationIshutterEnum,
+	FlowequationIsl1l2Enum,
+	FlowequationIsmacayealpattynEnum,
+	FlowequationIsstokesEnum,
+	FlowequationVertexEquationEnum,
+	FrictionCoefficientEnum,
+	FrictionPEnum,
+	FrictionQEnum,
+	GeometryHydrostaticRatioEnum,
+	HydrologyModelEnum,
+	HydrologyshreveEnum,
+	HydrologyshreveCREnum,
+	HydrologyshreveKnEnum,
+	HydrologyshreveNEnum,
+	HydrologyshrevePEnum,
+	HydrologyshreveQEnum,
+	HydrologyshreveSpcwatercolumnEnum,
+	HydrologyshreveStabilizationEnum,
+	HydrologydcEnum,
+	SedimentHeadEnum,
+	SedimentHeadOldEnum,
+	SedimentHeadResidualEnum,
+	EplHeadEnum,
+	EplHeadOldEnum,
+  HydrologydcRelTolEnum,
+	HydrologydcSpcsedimentHeadEnum,
+	HydrologydcSedimentCompressibilityEnum,
+	HydrologydcSedimentPorosityEnum,
+	HydrologydcSedimentThicknessEnum,
+	HydrologydcSedimentTransmitivityEnum,
+	HydrologydcWaterCompressibilityEnum,
+	HydrologydcSpceplHeadEnum,
+	HydrologydcMaskEplactiveEnum,
+	HydrologydcEplCompressibilityEnum,
+	HydrologydcEplPorosityEnum,
+	HydrologydcEplThicknessEnum,
+	HydrologydcEplTransmitivityEnum,
+	HydrologydcIsefficientlayerEnum,
+	HydrologydcSedimentlimitFlagEnum,
+	HydrologydcSedimentlimitEnum,
+	HydrologydcTransferFlagEnum,
+	HydrologydcLeakageFactorEnum,
+	HydrologydcPenaltyFactorEnum,
+	HydrologyLayerEnum,
+	HydrologySedimentEnum,
+	HydrologyEfficientEnum,
+	HydrologySedimentKmaxEnum,
+	BasisIntegralEnum,
+	WaterTransferEnum,
+	IndependentObjectEnum,
+	InversionControlParametersEnum,
+	InversionCostFunctionThresholdEnum,
+	InversionCostFunctionsCoefficientsEnum,
+	InversionCostFunctionsEnum,
+	InversionGradientOnlyEnum,
+	InversionGradientScalingEnum,
+	InversionIscontrolEnum,
+	InversionTaoEnum,
+	InversionIncompleteAdjointEnum,
+	InversionMaxParametersEnum,
+	InversionMaxiterPerStepEnum,
+	InversionMinParametersEnum,
+	InversionNstepsEnum,
+	InversionNumControlParametersEnum,
+	InversionNumCostFunctionsEnum,
+	InversionStepThresholdEnum,
+	InversionThicknessObsEnum,
+	InversionVelObsEnum,
+	InversionVxObsEnum,
+	InversionVyObsEnum,
+	InversionVzObsEnum,
+	MaskElementonfloatingiceEnum,
+	MaskElementongroundediceEnum,
+	MaskElementonwaterEnum,
+	MaskVertexonfloatingiceEnum,
+	MaskVertexongroundediceEnum,
+	MaskVertexonwaterEnum,
+	MaterialsBetaEnum,
+	MaterialsHeatcapacityEnum,
+	MaterialsLatentheatEnum,
+	MaterialsMeltingpointEnum,
+	MaterialsMixedLayerCapacityEnum,
+	MaterialsRheologyBEnum,
+	MaterialsRheologyBbarEnum,
+	MaterialsRheologyLawEnum,
+	MaterialsRheologyNEnum,
+	MaterialsRheologyZEnum,
+	MaterialsRheologyZbarEnum,
+	MaterialsRhoIceEnum,
+	MaterialsRhoWaterEnum,
+	MaterialsRhoFreshwaterEnum,
+	MaterialsMuWaterEnum,
+	MaterialsThermalExchangeVelocityEnum,
+	MaterialsThermalconductivityEnum,
+	MaterialsLithosphereShearModulusEnum,
+	MaterialsLithosphereDensityEnum,
+	MaterialsMantleShearModulusEnum,
+	MaterialsMantleDensityEnum,
+	MeshAverageVertexConnectivityEnum,
+	MeshDimensionEnum,
+	MeshEdgesEnum,
+	MeshElementconnectivityEnum,
+	MeshElementonbedEnum,
+	MeshElementonsurfaceEnum,
+	MeshElements2dEnum,
+	MeshElementsEnum,
+	MeshLowerelementsEnum,
+	MeshNumberofedgesEnum,
+	MeshNumberofelements2dEnum,
+	MeshNumberofelementsEnum,
+	MeshNumberoflayersEnum,
+	MeshNumberofvertices2dEnum,
+	MeshNumberofverticesEnum,
+	MeshUpperelementsEnum,
+	MeshVertexonbedEnum,
+	MeshVertexonsurfaceEnum,
+	MeshXEnum,
+	MeshYEnum,
+	MeshZEnum,
+	MiscellaneousNameEnum, //FIXME: only used by qmu, should not be marshalled (already in queueing script)
+	PrognosticHydrostaticAdjustmentEnum,
+	PrognosticMinThicknessEnum,
+	PrognosticPenaltyFactorEnum,
+	PrognosticSpcthicknessEnum,
+	PrognosticStabilizationEnum,
+	PrognosticVertexPairingEnum,
+	PrognosticNumRequestedOutputsEnum,
+	PrognosticRequestedOutputsEnum,
+	QmuIsdakotaEnum,
+	MassFluxSegmentsEnum,
+	MassFluxSegmentsPresentEnum,
+	QmuMassFluxSegmentsPresentEnum,
+	QmuNumberofpartitionsEnum,
+	QmuNumberofresponsesEnum,
+	QmuPartitionEnum,
+	QmuResponsedescriptorsEnum,
+	QmuVariabledescriptorsEnum,
+	QmuMaterialsRheologyBEnum,
+	RiftsNumriftsEnum,
+	RiftsRiftstructEnum,
+	SettingsIoGatherEnum,
+	SettingsLowmemEnum,
+	SettingsOutputFrequencyEnum,
+	SettingsResultsAsPatchesEnum,
+	SettingsWaitonlockEnum,
+	SurfaceforcingsDelta18oEnum,
+	SurfaceforcingsDelta18oSurfaceEnum,
+	SurfaceforcingsIsdelta18oEnum,
+	SurfaceforcingsPrecipitationsPresentdayEnum,
+	SurfaceforcingsTemperaturesPresentdayEnum,
+	SurfaceforcingsTemperaturesLgmEnum,
+	DebugProfilingEnum,
+	ProfilingCurrentMemEnum,
+	ProfilingCurrentFlopsEnum,
+	ProfilingSolutionTimeEnum,
+	MaxIterationConvergenceFlagEnum,
+	SteadystateMaxiterEnum,
+	SteadystateNumRequestedOutputsEnum,
+	SteadystateReltolEnum,
+	SteadystateRequestedOutputsEnum,
+	SurfaceEnum,
+	SurfaceforcingsPrecipitationEnum,
+	SurfaceforcingsMassBalanceEnum,
+	SurfaceforcingsIspddEnum,
+	SurfaceforcingsDesfacEnum,
+	SurfaceforcingsS0pEnum,
+	SurfaceforcingsIssmbgradientsEnum,
+	SurfaceforcingsMonthlytemperaturesEnum,
+	SurfaceforcingsHrefEnum,
+	SurfaceforcingsSmbrefEnum,
+	SurfaceforcingsBPosEnum,
+	SurfaceforcingsBNegEnum,
+	ThermalMaxiterEnum,
+	ThermalPenaltyFactorEnum,
+	ThermalPenaltyLockEnum,
+	ThermalPenaltyThresholdEnum,
+	ThermalSpctemperatureEnum,
+	ThermalStabilizationEnum,
+	ThermalIsenthalpyEnum,
+	GiaMantleViscosityEnum,
+	GiaLithosphereThicknessEnum,
+	ThicknessEnum,
+	TimesteppingStartTimeEnum,
+	TimesteppingFinalTimeEnum,
+	TimesteppingCflCoefficientEnum,
+	TimesteppingTimeAdaptEnum,
+	TimesteppingTimeStepEnum,
+	TransientIsdiagnosticEnum,
+	TransientIsgroundinglineEnum,
+	TransientIsprognosticEnum,
+	TransientIsthermalEnum,
+	TransientIsgiaEnum,
+	TransientNumRequestedOutputsEnum,
+	TransientRequestedOutputsEnum,
+	/*}}}*/
+	/*Solutions and Analyses{{{ */
+	SolutionTypeEnum,
+	AnalysisTypeEnum,
+	ConfigurationTypeEnum,
+	AdjointBalancethicknessAnalysisEnum,
+	AdjointHorizAnalysisEnum,
+	AdjointSolutionEnum,
+	AnalysisCounterEnum,
+	NoneAnalysisEnum,
+	DefaultAnalysisEnum,
+	BalancethicknessAnalysisEnum,
+	BalancethicknessSolutionEnum,
+	BalancethicknessSoftAnalysisEnum,
+	BalancethicknessSoftSolutionEnum,
+	BedSlopeAnalysisEnum,
+	BedSlopeSolutionEnum,
+	BedSlopeXAnalysisEnum,
+	BedSlopeYAnalysisEnum,
+	DiagnosticHorizAnalysisEnum,
+	DiagnosticHutterAnalysisEnum,
+	DiagnosticSolutionEnum,
+	DiagnosticVertAnalysisEnum,
+	EnthalpyAnalysisEnum,
+	EnthalpySolutionEnum,
+	FlaimAnalysisEnum,
+	FlaimSolutionEnum,
+	HydrologyShreveAnalysisEnum,
+	HydrologyDCInefficientAnalysisEnum,
+	HydrologyDCEfficientAnalysisEnum,
+	HydrologySolutionEnum,
+	MeltingAnalysisEnum,
+	PrognosticAnalysisEnum,
+	PrognosticSolutionEnum,
+	SteadystateSolutionEnum,
+	SurfaceSlopeAnalysisEnum,
+	SurfaceSlopeSolutionEnum,
+	SurfaceSlopeXAnalysisEnum,
+	SurfaceSlopeYAnalysisEnum,
+	ThermalAnalysisEnum,
+	ThermalSolutionEnum,
+	TransientSolutionEnum,
+	GiaSolutionEnum,
+	GiaAnalysisEnum,
+	/*}}}*/
+	/*Approximations {{{*/
+	ApproximationEnum,
+	NoneApproximationEnum,
+	HutterApproximationEnum,
+	MacAyealApproximationEnum,
+	MacAyealPattynApproximationEnum,
+	MacAyealStokesApproximationEnum,
+	L1L2ApproximationEnum,
+	PattynApproximationEnum,
+	PattynStokesApproximationEnum,
+	StokesApproximationEnum,
+	/*}}}*/
+	/*Datasets {{{*/
+	ConstraintsEnum,
+	LoadsEnum,
+	MaterialsEnum,
+	NodesEnum,
+	ContoursEnum,
+	ParametersEnum,
+	VerticesEnum,
+	ResultsEnum,
+	/*}}}*/
+	/*Objects {{{*/
+	GenericParamEnum,
+	AdolcParamEnum,
+	BoolInputEnum,
+	BoolParamEnum,
+	ContourEnum,
+	ControlInputEnum,
+	DatasetInputEnum,
+	DofIndexingEnum,
+	DoubleInputEnum,
+	DataSetParamEnum,
+	DoubleMatArrayParamEnum,
+	DoubleMatParamEnum,
+	DoubleParamEnum,
+	DoubleVecParamEnum,
+	ElementEnum,
+	ElementResultEnum,
+	ExternalResultEnum,
+	FileParamEnum,
+	HookEnum,
+	IcefrontEnum,
+	InputEnum,
+	IntInputEnum,
+	IntParamEnum,
+	IntVecParamEnum,
+	TransientParamEnum,
+	IceFrontTypeEnum,
+	MacAyeal2dIceFrontEnum,
+	MacAyeal3dIceFrontEnum,
+	MaticeEnum,
+	MatdamageiceEnum,
+	MatparEnum,
+	NodeEnum,
+	NumericalfluxEnum,
+	NumericalfluxTypeEnum,
+	ParamEnum,
+	L1L2IceFrontEnum,
+	PattynIceFrontEnum,
+	PengridEnum,
+	PenpairEnum,
+	PentaEnum,
+	PentaP1InputEnum,
+	ProfilerEnum,
+	MatrixParamEnum,
+	NodeSIdEnum,
+	VectorParamEnum,
+	RiftfrontEnum,
+	RiftfrontTypeEnum,
+	SegmentEnum,
+	SegmentRiftfrontEnum,
+	SpcDynamicEnum,
+	SpcStaticEnum,
+	SpcTransientEnum,
+	StokesIceFrontEnum,
+	StringArrayParamEnum,
+	StringParamEnum,
+	TriaEnum,
+	TriaInputEnum,
+	VertexEnum,
+	VertexPIdEnum,
+	VertexSIdEnum,
+	/*}}}*/
+	/*Fill {{{*/
+	AirEnum,
+	IceEnum,
+	MelangeEnum,
+	WaterEnum,
+	/*}}}*/
+	/*Rift state {{{*/
+	ClosedEnum,
+	FreeEnum,
+	OpenEnum,
+	/*}}}*/
+	/*Inputs {{{*/
+	AdjointpEnum,
+	AdjointxEnum,
+	AdjointyEnum,
+	AdjointzEnum,
+	BalancethicknessMisfitEnum,
+	BedSlopeXEnum,
+	BedSlopeYEnum,
+	BoundaryEnum,
+	ConstantEnum,
+	ConvergedEnum,
+	FillEnum,
+	FractionIncrementEnum,
+	FrictionEnum,
+	GroundinglineMeltingRateEnum,
+	InternalEnum,
+	MassFluxEnum,
+	MaxPenetrationEnum,
+	MeltingOffsetEnum,
+	MisfitEnum,
+	NumberNodeToElementConnectivityEnum,
+	PressureEnum,
+	PressurePicardEnum,
+	QmuPressureEnum,
+	QmuVxEnum,
+	QmuVyEnum,
+	QmuVzEnum,
+	QmuThicknessEnum,
+	QmuBedEnum,
+	QmuSurfaceEnum,
+	QmuMeltingEnum,
+	QmuVxMeshEnum,
+	QmuVyMeshEnum,
+	QmuVzMeshEnum,
+	AndroidFrictionCoefficientEnum,
+	ResetPenaltiesEnum,
+	SegmentOnIceShelfEnum,
+	SurfaceAbsVelMisfitEnum,
+	SurfaceAreaEnum,
+	SurfaceAverageVelMisfitEnum,
+	SurfaceLogVelMisfitEnum,
+	SurfaceLogVxVyMisfitEnum,
+	SurfaceRelVelMisfitEnum,
+	SurfaceSlopeXEnum,
+	SurfaceSlopeYEnum,
+	TemperatureEnum,
+	TemperatureOldEnum,
+	TemperaturePicardEnum,
+	ThicknessAbsMisfitEnum,
+	VelEnum,
+	VelocityEnum,
+	VxAverageEnum,
+	VxEnum,
+	VxPicardEnum,
+	VyAverageEnum,
+	VyEnum,
+	VyPicardEnum,
+	VzEnum,
+	VzMacAyealEnum,
+	VzPattynEnum,
+	VzPicardEnum,
+	VzStokesEnum,
+	VxMeshEnum,
+	VyMeshEnum,
+	VzMeshEnum,
+	EnthalpyEnum,
+	EnthalpyPicardEnum,
+	ThicknessAbsGradientEnum,
+	ThicknessAlongGradientEnum,
+	ThicknessAcrossGradientEnum,
+	StepResponsesEnum,
+	IntMatParamEnum,
+	RheologyBbarAbsGradientEnum,
+	DragCoefficientAbsGradientEnum,
+	TransientInputEnum,
+	WaterfractionEnum,
+	WatercolumnEnum,
+	BasalFrictionEnum,
+	ViscousHeatingEnum,
+	QmuTemperatureEnum,
+	HydrologyWaterVxEnum,
+	HydrologyWaterVyEnum,
+	StressTensorEnum,
+	StressTensorxxEnum,
+	StressTensorxyEnum,
+	StressTensorxzEnum,
+	StressTensoryyEnum,
+	StressTensoryzEnum,
+	StressTensorzzEnum,
+	GiaCrossSectionShapeEnum,
+	GiadWdtEnum,
+	GiaWEnum,
+	/*}}}*/
+	/*Element Interpolations{{{*/
+	P0Enum,
+	P1Enum,
+	P1DGEnum,
+	MINIEnum,
+	P2Enum,
+	/*}}}*/
+	/*Results{{{*/
+	SaveResultsEnum,
+	BoolElementResultEnum,
+	BoolExternalResultEnum,
+	DoubleElementResultEnum,
+	DoubleExternalResultEnum,
+	DoubleMatExternalResultEnum,
+	IntExternalResultEnum,
+	JEnum,
+	PatchEnum,
+	PatchNodesEnum,
+	PatchVerticesEnum,
+	PentaP1ElementResultEnum,
+	StringExternalResultEnum,
+	StepEnum,
+	TimeEnum,
+	TriaP1ElementResultEnum,
+	WaterColumnOldEnum,
+	/*}}}*/
+	/*Responses{{{*/
+	MinVelEnum,
+	MaxVelEnum,
+	MinVxEnum,
+	MaxVxEnum,
+	MaxAbsVxEnum,
+	MinVyEnum,
+	MaxVyEnum,
+	MaxAbsVyEnum,
+	MinVzEnum,
+	MaxVzEnum,
+	MaxAbsVzEnum,
+	IceVolumeEnum,
+	TotalSmbEnum,
+	/*}}}*/
+	/*Relaxation{{{*/
+	AbsoluteEnum,
+	IncrementalEnum,
+	/*}}}*/
+	/*Grounding Line{{{*/
+	AgressiveMigrationEnum,
+	NoneEnum,
+	SoftMigrationEnum,
+	SubelementMigrationEnum,
+	SubelementMigration2Enum,
+	GLlevelsetEnum,
+	/*}}}*/
+	/*Solver{{{*/
+	StokesSolverEnum,
+	/*}}}*/
+	/*Parameters{{{*/
+	AdjointEnum,
+	ColinearEnum,
+	ControlSteadyEnum,
+	FsetEnum,
+	Gradient1Enum,
+	Gradient2Enum,
+	Gradient3Enum,
+	GradientEnum,
+	GroundinglineMigrationEnum,
+	GsetEnum,
+	IndexEnum,
+	IndexedEnum,
+	IntersectEnum,
+	NodalEnum,
+	OldGradientEnum,
+	OutputFilePointerEnum,
+	OutputFileNameEnum,
+	LockFileNameEnum,
+	ToolkitsOptionsAnalysesEnum,
+	ToolkitsOptionsStringsEnum,
+	QmuErrNameEnum,
+	QmuInNameEnum,
+	QmuOutNameEnum,
+	RegularEnum,
+	ScaledEnum,
+	SeparateEnum,
+	SsetEnum,
+	VerboseEnum,
+	/*}}}*/
+	/*Interpolation {{{*/
+	TriangleInterpEnum,
+	BilinearInterpEnum,
+	NearestInterpEnum,
+	/*}}}*/
+	/*Coordinate Systems{{{*/
+	XYEnum,
+	XYZPEnum,
+	/*}}}*/
+	/*Toolkits{{{*/
+	DenseEnum,
+	MpiDenseEnum,
+	SeqEnum,
+	MpiEnum,
+	/*}}}*/
+	/*Options{{{*/
+	OptionEnum,
+	GenericOptionEnum,
+	OptionCellEnum,
+	OptionCharEnum,
+	OptionStructEnum,
+	OptionDoubleEnum,
+	OptionLogicalEnum,
+	/*}}}*/
+	/*Rheology law (move too Material) {{{*/
+	PatersonEnum,
+	ArrheniusEnum,
+	/*}}}*/
+	MaximumNumberOfEnums
+};
+
+#endif
Index: /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp
===================================================================
--- /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 15396)
+++ /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 15396)
@@ -0,0 +1,593 @@
+/*
+* \file EnumToStringx.cpp:
+* \brief: output string associated with enum
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include <cstring>
+#include "./Enum.h"
+#include "../Exceptions/exceptions.h"
+#include "../MemOps/MemOps.h"
+
+const char* EnumToStringx(int en){
+
+	switch(en){
+
+		case AutodiffIsautodiffEnum : return "AutodiffIsautodiff";
+		case AutodiffNumDependentsEnum : return "AutodiffNumDependents";
+		case AutodiffNumDependentObjectsEnum : return "AutodiffNumDependentObjects";
+		case AutodiffDependentObjectNamesEnum : return "AutodiffDependentObjectNames";
+		case AutodiffDependentObjectTypesEnum : return "AutodiffDependentObjectTypes";
+		case AutodiffDependentObjectIndicesEnum : return "AutodiffDependentObjectIndices";
+		case AutodiffDependentObjectsEnum : return "AutodiffDependentObjects";
+		case AutodiffNumIndependentsEnum : return "AutodiffNumIndependents";
+		case AutodiffNumIndependentObjectsEnum : return "AutodiffNumIndependentObjects";
+		case AutodiffIndependentObjectNamesEnum : return "AutodiffIndependentObjectNames";
+		case AutodiffIndependentObjectTypesEnum : return "AutodiffIndependentObjectTypes";
+		case AutodiffIndependentObjectsEnum : return "AutodiffIndependentObjects";
+		case AutodiffJacobianEnum : return "AutodiffJacobian";
+		case AutodiffXpEnum : return "AutodiffXp";
+		case AutodiffDriverEnum : return "AutodiffDriver";
+		case AutodiffFosForwardIndexEnum : return "AutodiffFosForwardIndex";
+		case AutodiffFovForwardIndicesEnum : return "AutodiffFovForwardIndices";
+		case AutodiffFosReverseIndexEnum : return "AutodiffFosReverseIndex";
+		case AutodiffMassFluxSegmentsPresentEnum : return "AutodiffMassFluxSegmentsPresent";
+		case AutodiffKeepEnum : return "AutodiffKeep";
+		case BalancethicknessSpcthicknessEnum : return "BalancethicknessSpcthickness";
+		case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
+		case BalancethicknessThickeningRateEnum : return "BalancethicknessThickeningRate";
+		case BasalforcingsGeothermalfluxEnum : return "BasalforcingsGeothermalflux";
+		case BasalforcingsMeltingRateCorrectionEnum : return "BasalforcingsMeltingRateCorrection";
+		case BasalforcingsMeltingRateEnum : return "BasalforcingsMeltingRate";
+		case BathymetryEnum : return "Bathymetry";
+		case BedEnum : return "Bed";
+		case ConstantsGEnum : return "ConstantsG";
+		case ConstantsReferencetemperatureEnum : return "ConstantsReferencetemperature";
+		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 LoadingforceXEnum : return "LoadingforceX";
+		case LoadingforceYEnum : return "LoadingforceY";
+		case LoadingforceZEnum : return "LoadingforceZ";
+		case FlowequationBordermacayealEnum : return "FlowequationBordermacayeal";
+		case FlowequationBorderpattynEnum : return "FlowequationBorderpattyn";
+		case FlowequationBorderstokesEnum : return "FlowequationBorderstokes";
+		case FlowequationElementEquationEnum : return "FlowequationElementEquation";
+		case FlowequationIshutterEnum : return "FlowequationIshutter";
+		case FlowequationIsl1l2Enum : return "FlowequationIsl1l2";
+		case FlowequationIsmacayealpattynEnum : return "FlowequationIsmacayealpattyn";
+		case FlowequationIsstokesEnum : return "FlowequationIsstokes";
+		case FlowequationVertexEquationEnum : return "FlowequationVertexEquation";
+		case FrictionCoefficientEnum : return "FrictionCoefficient";
+		case FrictionPEnum : return "FrictionP";
+		case FrictionQEnum : return "FrictionQ";
+		case GeometryHydrostaticRatioEnum : return "GeometryHydrostaticRatio";
+		case HydrologyModelEnum : return "HydrologyModel";
+		case HydrologyshreveEnum : return "Hydrologyshreve";
+		case HydrologyshreveCREnum : return "HydrologyshreveCR";
+		case HydrologyshreveKnEnum : return "HydrologyshreveKn";
+		case HydrologyshreveNEnum : return "HydrologyshreveN";
+		case HydrologyshrevePEnum : return "HydrologyshreveP";
+		case HydrologyshreveQEnum : return "HydrologyshreveQ";
+		case HydrologyshreveSpcwatercolumnEnum : return "HydrologyshreveSpcwatercolumn";
+		case HydrologyshreveStabilizationEnum : return "HydrologyshreveStabilization";
+		case HydrologydcEnum : return "Hydrologydc";
+		case SedimentHeadEnum : return "SedimentHead";
+		case SedimentHeadOldEnum : return "SedimentHeadOld";
+		case SedimentHeadResidualEnum : return "SedimentHeadResidual";
+		case EplHeadEnum : return "EplHead";
+		case EplHeadOldEnum : return "EplHeadOld";
+		case HydrologydcRelTolEnum : return "HydrologydcRelTol";
+		case HydrologydcSpcsedimentHeadEnum : return "HydrologydcSpcsedimentHead";
+		case HydrologydcSedimentCompressibilityEnum : return "HydrologydcSedimentCompressibility";
+		case HydrologydcSedimentPorosityEnum : return "HydrologydcSedimentPorosity";
+		case HydrologydcSedimentThicknessEnum : return "HydrologydcSedimentThickness";
+		case HydrologydcSedimentTransmitivityEnum : return "HydrologydcSedimentTransmitivity";
+		case HydrologydcWaterCompressibilityEnum : return "HydrologydcWaterCompressibility";
+		case HydrologydcSpceplHeadEnum : return "HydrologydcSpceplHead";
+		case HydrologydcMaskEplactiveEnum : return "HydrologydcMaskEplactive";
+		case HydrologydcEplCompressibilityEnum : return "HydrologydcEplCompressibility";
+		case HydrologydcEplPorosityEnum : return "HydrologydcEplPorosity";
+		case HydrologydcEplThicknessEnum : return "HydrologydcEplThickness";
+		case HydrologydcEplTransmitivityEnum : return "HydrologydcEplTransmitivity";
+		case HydrologydcIsefficientlayerEnum : return "HydrologydcIsefficientlayer";
+		case HydrologydcSedimentlimitFlagEnum : return "HydrologydcSedimentlimitFlag";
+		case HydrologydcSedimentlimitEnum : return "HydrologydcSedimentlimit";
+		case HydrologydcTransferFlagEnum : return "HydrologydcTransferFlag";
+		case HydrologydcLeakageFactorEnum : return "HydrologydcLeakageFactor";
+		case HydrologydcPenaltyFactorEnum : return "HydrologydcPenaltyFactor";
+		case HydrologyLayerEnum : return "HydrologyLayer";
+		case HydrologySedimentEnum : return "HydrologySediment";
+		case HydrologyEfficientEnum : return "HydrologyEfficient";
+		case HydrologySedimentKmaxEnum : return "HydrologySedimentKmax";
+		case BasisIntegralEnum : return "BasisIntegral";
+		case WaterTransferEnum : return "WaterTransfer";
+		case IndependentObjectEnum : return "IndependentObject";
+		case InversionControlParametersEnum : return "InversionControlParameters";
+		case InversionCostFunctionThresholdEnum : return "InversionCostFunctionThreshold";
+		case InversionCostFunctionsCoefficientsEnum : return "InversionCostFunctionsCoefficients";
+		case InversionCostFunctionsEnum : return "InversionCostFunctions";
+		case InversionGradientOnlyEnum : return "InversionGradientOnly";
+		case InversionGradientScalingEnum : return "InversionGradientScaling";
+		case InversionIscontrolEnum : return "InversionIscontrol";
+		case InversionTaoEnum : return "InversionTao";
+		case InversionIncompleteAdjointEnum : return "InversionIncompleteAdjoint";
+		case InversionMaxParametersEnum : return "InversionMaxParameters";
+		case InversionMaxiterPerStepEnum : return "InversionMaxiterPerStep";
+		case InversionMinParametersEnum : return "InversionMinParameters";
+		case InversionNstepsEnum : return "InversionNsteps";
+		case InversionNumControlParametersEnum : return "InversionNumControlParameters";
+		case InversionNumCostFunctionsEnum : return "InversionNumCostFunctions";
+		case InversionStepThresholdEnum : return "InversionStepThreshold";
+		case InversionThicknessObsEnum : return "InversionThicknessObs";
+		case InversionVelObsEnum : return "InversionVelObs";
+		case InversionVxObsEnum : return "InversionVxObs";
+		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 MaterialsBetaEnum : return "MaterialsBeta";
+		case MaterialsHeatcapacityEnum : return "MaterialsHeatcapacity";
+		case MaterialsLatentheatEnum : return "MaterialsLatentheat";
+		case MaterialsMeltingpointEnum : return "MaterialsMeltingpoint";
+		case MaterialsMixedLayerCapacityEnum : return "MaterialsMixedLayerCapacity";
+		case MaterialsRheologyBEnum : return "MaterialsRheologyB";
+		case MaterialsRheologyBbarEnum : return "MaterialsRheologyBbar";
+		case MaterialsRheologyLawEnum : return "MaterialsRheologyLaw";
+		case MaterialsRheologyNEnum : return "MaterialsRheologyN";
+		case MaterialsRheologyZEnum : return "MaterialsRheologyZ";
+		case MaterialsRheologyZbarEnum : return "MaterialsRheologyZbar";
+		case MaterialsRhoIceEnum : return "MaterialsRhoIce";
+		case MaterialsRhoWaterEnum : return "MaterialsRhoWater";
+		case MaterialsRhoFreshwaterEnum : return "MaterialsRhoFreshwater";
+		case MaterialsMuWaterEnum : return "MaterialsMuWater";
+		case MaterialsThermalExchangeVelocityEnum : return "MaterialsThermalExchangeVelocity";
+		case MaterialsThermalconductivityEnum : return "MaterialsThermalconductivity";
+		case MaterialsLithosphereShearModulusEnum : return "MaterialsLithosphereShearModulus";
+		case MaterialsLithosphereDensityEnum : return "MaterialsLithosphereDensity";
+		case MaterialsMantleShearModulusEnum : return "MaterialsMantleShearModulus";
+		case MaterialsMantleDensityEnum : return "MaterialsMantleDensity";
+		case MeshAverageVertexConnectivityEnum : return "MeshAverageVertexConnectivity";
+		case MeshDimensionEnum : return "MeshDimension";
+		case MeshEdgesEnum : return "MeshEdges";
+		case MeshElementconnectivityEnum : return "MeshElementconnectivity";
+		case MeshElementonbedEnum : return "MeshElementonbed";
+		case MeshElementonsurfaceEnum : return "MeshElementonsurface";
+		case MeshElements2dEnum : return "MeshElements2d";
+		case MeshElementsEnum : return "MeshElements";
+		case MeshLowerelementsEnum : return "MeshLowerelements";
+		case MeshNumberofedgesEnum : return "MeshNumberofedges";
+		case MeshNumberofelements2dEnum : return "MeshNumberofelements2d";
+		case MeshNumberofelementsEnum : return "MeshNumberofelements";
+		case MeshNumberoflayersEnum : return "MeshNumberoflayers";
+		case MeshNumberofvertices2dEnum : return "MeshNumberofvertices2d";
+		case MeshNumberofverticesEnum : return "MeshNumberofvertices";
+		case MeshUpperelementsEnum : return "MeshUpperelements";
+		case MeshVertexonbedEnum : return "MeshVertexonbed";
+		case MeshVertexonsurfaceEnum : return "MeshVertexonsurface";
+		case MeshXEnum : return "MeshX";
+		case MeshYEnum : return "MeshY";
+		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 QmuIsdakotaEnum : return "QmuIsdakota";
+		case MassFluxSegmentsEnum : return "MassFluxSegments";
+		case MassFluxSegmentsPresentEnum : return "MassFluxSegmentsPresent";
+		case QmuMassFluxSegmentsPresentEnum : return "QmuMassFluxSegmentsPresent";
+		case QmuNumberofpartitionsEnum : return "QmuNumberofpartitions";
+		case QmuNumberofresponsesEnum : return "QmuNumberofresponses";
+		case QmuPartitionEnum : return "QmuPartition";
+		case QmuResponsedescriptorsEnum : return "QmuResponsedescriptors";
+		case QmuVariabledescriptorsEnum : return "QmuVariabledescriptors";
+		case QmuMaterialsRheologyBEnum : return "QmuMaterialsRheologyB";
+		case RiftsNumriftsEnum : return "RiftsNumrifts";
+		case RiftsRiftstructEnum : return "RiftsRiftstruct";
+		case SettingsIoGatherEnum : return "SettingsIoGather";
+		case SettingsLowmemEnum : return "SettingsLowmem";
+		case SettingsOutputFrequencyEnum : return "SettingsOutputFrequency";
+		case SettingsResultsAsPatchesEnum : return "SettingsResultsAsPatches";
+		case SettingsWaitonlockEnum : return "SettingsWaitonlock";
+		case SurfaceforcingsDelta18oEnum : return "SurfaceforcingsDelta18o";
+		case SurfaceforcingsDelta18oSurfaceEnum : return "SurfaceforcingsDelta18oSurface";
+		case SurfaceforcingsIsdelta18oEnum : return "SurfaceforcingsIsdelta18o";
+		case SurfaceforcingsPrecipitationsPresentdayEnum : return "SurfaceforcingsPrecipitationsPresentday";
+		case SurfaceforcingsTemperaturesPresentdayEnum : return "SurfaceforcingsTemperaturesPresentday";
+		case SurfaceforcingsTemperaturesLgmEnum : return "SurfaceforcingsTemperaturesLgm";
+		case DebugProfilingEnum : return "DebugProfiling";
+		case ProfilingCurrentMemEnum : return "ProfilingCurrentMem";
+		case ProfilingCurrentFlopsEnum : return "ProfilingCurrentFlops";
+		case ProfilingSolutionTimeEnum : return "ProfilingSolutionTime";
+		case MaxIterationConvergenceFlagEnum : return "MaxIterationConvergenceFlag";
+		case SteadystateMaxiterEnum : return "SteadystateMaxiter";
+		case SteadystateNumRequestedOutputsEnum : return "SteadystateNumRequestedOutputs";
+		case SteadystateReltolEnum : return "SteadystateReltol";
+		case SteadystateRequestedOutputsEnum : return "SteadystateRequestedOutputs";
+		case SurfaceEnum : return "Surface";
+		case SurfaceforcingsPrecipitationEnum : return "SurfaceforcingsPrecipitation";
+		case SurfaceforcingsMassBalanceEnum : return "SurfaceforcingsMassBalance";
+		case SurfaceforcingsIspddEnum : return "SurfaceforcingsIspdd";
+		case SurfaceforcingsDesfacEnum : return "SurfaceforcingsDesfac";
+		case SurfaceforcingsS0pEnum : return "SurfaceforcingsS0p";
+		case SurfaceforcingsIssmbgradientsEnum : return "SurfaceforcingsIssmbgradients";
+		case SurfaceforcingsMonthlytemperaturesEnum : return "SurfaceforcingsMonthlytemperatures";
+		case SurfaceforcingsHrefEnum : return "SurfaceforcingsHref";
+		case SurfaceforcingsSmbrefEnum : return "SurfaceforcingsSmbref";
+		case SurfaceforcingsBPosEnum : return "SurfaceforcingsBPos";
+		case SurfaceforcingsBNegEnum : return "SurfaceforcingsBNeg";
+		case ThermalMaxiterEnum : return "ThermalMaxiter";
+		case ThermalPenaltyFactorEnum : return "ThermalPenaltyFactor";
+		case ThermalPenaltyLockEnum : return "ThermalPenaltyLock";
+		case ThermalPenaltyThresholdEnum : return "ThermalPenaltyThreshold";
+		case ThermalSpctemperatureEnum : return "ThermalSpctemperature";
+		case ThermalStabilizationEnum : return "ThermalStabilization";
+		case ThermalIsenthalpyEnum : return "ThermalIsenthalpy";
+		case GiaMantleViscosityEnum : return "GiaMantleViscosity";
+		case GiaLithosphereThicknessEnum : return "GiaLithosphereThickness";
+		case ThicknessEnum : return "Thickness";
+		case TimesteppingStartTimeEnum : return "TimesteppingStartTime";
+		case TimesteppingFinalTimeEnum : return "TimesteppingFinalTime";
+		case TimesteppingCflCoefficientEnum : return "TimesteppingCflCoefficient";
+		case TimesteppingTimeAdaptEnum : return "TimesteppingTimeAdapt";
+		case TimesteppingTimeStepEnum : return "TimesteppingTimeStep";
+		case TransientIsdiagnosticEnum : return "TransientIsdiagnostic";
+		case TransientIsgroundinglineEnum : return "TransientIsgroundingline";
+		case TransientIsprognosticEnum : return "TransientIsprognostic";
+		case TransientIsthermalEnum : return "TransientIsthermal";
+		case TransientIsgiaEnum : return "TransientIsgia";
+		case TransientNumRequestedOutputsEnum : return "TransientNumRequestedOutputs";
+		case TransientRequestedOutputsEnum : return "TransientRequestedOutputs";
+		case SolutionTypeEnum : return "SolutionType";
+		case AnalysisTypeEnum : return "AnalysisType";
+		case ConfigurationTypeEnum : return "ConfigurationType";
+		case AdjointBalancethicknessAnalysisEnum : return "AdjointBalancethicknessAnalysis";
+		case AdjointHorizAnalysisEnum : return "AdjointHorizAnalysis";
+		case AdjointSolutionEnum : return "AdjointSolution";
+		case AnalysisCounterEnum : return "AnalysisCounter";
+		case NoneAnalysisEnum : return "NoneAnalysis";
+		case DefaultAnalysisEnum : return "DefaultAnalysis";
+		case BalancethicknessAnalysisEnum : return "BalancethicknessAnalysis";
+		case BalancethicknessSolutionEnum : return "BalancethicknessSolution";
+		case BalancethicknessSoftAnalysisEnum : return "BalancethicknessSoftAnalysis";
+		case BalancethicknessSoftSolutionEnum : return "BalancethicknessSoftSolution";
+		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 EnthalpyAnalysisEnum : return "EnthalpyAnalysis";
+		case EnthalpySolutionEnum : return "EnthalpySolution";
+		case FlaimAnalysisEnum : return "FlaimAnalysis";
+		case FlaimSolutionEnum : return "FlaimSolution";
+		case HydrologyShreveAnalysisEnum : return "HydrologyShreveAnalysis";
+		case HydrologyDCInefficientAnalysisEnum : return "HydrologyDCInefficientAnalysis";
+		case HydrologyDCEfficientAnalysisEnum : return "HydrologyDCEfficientAnalysis";
+		case HydrologySolutionEnum : return "HydrologySolution";
+		case MeltingAnalysisEnum : return "MeltingAnalysis";
+		case PrognosticAnalysisEnum : return "PrognosticAnalysis";
+		case PrognosticSolutionEnum : return "PrognosticSolution";
+		case SteadystateSolutionEnum : return "SteadystateSolution";
+		case SurfaceSlopeAnalysisEnum : return "SurfaceSlopeAnalysis";
+		case SurfaceSlopeSolutionEnum : return "SurfaceSlopeSolution";
+		case SurfaceSlopeXAnalysisEnum : return "SurfaceSlopeXAnalysis";
+		case SurfaceSlopeYAnalysisEnum : return "SurfaceSlopeYAnalysis";
+		case ThermalAnalysisEnum : return "ThermalAnalysis";
+		case ThermalSolutionEnum : return "ThermalSolution";
+		case TransientSolutionEnum : return "TransientSolution";
+		case GiaSolutionEnum : return "GiaSolution";
+		case GiaAnalysisEnum : return "GiaAnalysis";
+		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 L1L2ApproximationEnum : return "L1L2Approximation";
+		case PattynApproximationEnum : return "PattynApproximation";
+		case PattynStokesApproximationEnum : return "PattynStokesApproximation";
+		case StokesApproximationEnum : return "StokesApproximation";
+		case ConstraintsEnum : return "Constraints";
+		case LoadsEnum : return "Loads";
+		case MaterialsEnum : return "Materials";
+		case NodesEnum : return "Nodes";
+		case ContoursEnum : return "Contours";
+		case ParametersEnum : return "Parameters";
+		case VerticesEnum : return "Vertices";
+		case ResultsEnum : return "Results";
+		case GenericParamEnum : return "GenericParam";
+		case AdolcParamEnum : return "AdolcParam";
+		case BoolInputEnum : return "BoolInput";
+		case BoolParamEnum : return "BoolParam";
+		case ContourEnum : return "Contour";
+		case ControlInputEnum : return "ControlInput";
+		case DatasetInputEnum : return "DatasetInput";
+		case DofIndexingEnum : return "DofIndexing";
+		case DoubleInputEnum : return "DoubleInput";
+		case DataSetParamEnum : return "DataSetParam";
+		case DoubleMatArrayParamEnum : return "DoubleMatArrayParam";
+		case DoubleMatParamEnum : return "DoubleMatParam";
+		case DoubleParamEnum : return "DoubleParam";
+		case DoubleVecParamEnum : return "DoubleVecParam";
+		case ElementEnum : return "Element";
+		case ElementResultEnum : return "ElementResult";
+		case ExternalResultEnum : return "ExternalResult";
+		case FileParamEnum : return "FileParam";
+		case HookEnum : return "Hook";
+		case IcefrontEnum : return "Icefront";
+		case InputEnum : return "Input";
+		case IntInputEnum : return "IntInput";
+		case IntParamEnum : return "IntParam";
+		case IntVecParamEnum : return "IntVecParam";
+		case TransientParamEnum : return "TransientParam";
+		case IceFrontTypeEnum : return "IceFrontType";
+		case MacAyeal2dIceFrontEnum : return "MacAyeal2dIceFront";
+		case MacAyeal3dIceFrontEnum : return "MacAyeal3dIceFront";
+		case MaticeEnum : return "Matice";
+		case MatdamageiceEnum : return "Matdamageice";
+		case MatparEnum : return "Matpar";
+		case NodeEnum : return "Node";
+		case NumericalfluxEnum : return "Numericalflux";
+		case NumericalfluxTypeEnum : return "NumericalfluxType";
+		case ParamEnum : return "Param";
+		case L1L2IceFrontEnum : return "L1L2IceFront";
+		case PattynIceFrontEnum : return "PattynIceFront";
+		case PengridEnum : return "Pengrid";
+		case PenpairEnum : return "Penpair";
+		case PentaEnum : return "Penta";
+		case PentaP1InputEnum : return "PentaP1Input";
+		case ProfilerEnum : return "Profiler";
+		case MatrixParamEnum : return "MatrixParam";
+		case NodeSIdEnum : return "NodeSId";
+		case VectorParamEnum : return "VectorParam";
+		case RiftfrontEnum : return "Riftfront";
+		case RiftfrontTypeEnum : return "RiftfrontType";
+		case SegmentEnum : return "Segment";
+		case SegmentRiftfrontEnum : return "SegmentRiftfront";
+		case SpcDynamicEnum : return "SpcDynamic";
+		case SpcStaticEnum : return "SpcStatic";
+		case SpcTransientEnum : return "SpcTransient";
+		case StokesIceFrontEnum : return "StokesIceFront";
+		case StringArrayParamEnum : return "StringArrayParam";
+		case StringParamEnum : return "StringParam";
+		case TriaEnum : return "Tria";
+		case TriaInputEnum : return "TriaInput";
+		case VertexEnum : return "Vertex";
+		case VertexPIdEnum : return "VertexPId";
+		case VertexSIdEnum : return "VertexSId";
+		case AirEnum : return "Air";
+		case IceEnum : return "Ice";
+		case MelangeEnum : return "Melange";
+		case WaterEnum : return "Water";
+		case ClosedEnum : return "Closed";
+		case FreeEnum : return "Free";
+		case OpenEnum : return "Open";
+		case AdjointpEnum : return "Adjointp";
+		case AdjointxEnum : return "Adjointx";
+		case AdjointyEnum : return "Adjointy";
+		case AdjointzEnum : return "Adjointz";
+		case BalancethicknessMisfitEnum : return "BalancethicknessMisfit";
+		case BedSlopeXEnum : return "BedSlopeX";
+		case BedSlopeYEnum : return "BedSlopeY";
+		case BoundaryEnum : return "Boundary";
+		case ConstantEnum : return "Constant";
+		case ConvergedEnum : return "Converged";
+		case FillEnum : return "Fill";
+		case FractionIncrementEnum : return "FractionIncrement";
+		case FrictionEnum : return "Friction";
+		case GroundinglineMeltingRateEnum : return "GroundinglineMeltingRate";
+		case InternalEnum : return "Internal";
+		case MassFluxEnum : return "MassFlux";
+		case MaxPenetrationEnum : return "MaxPenetration";
+		case MeltingOffsetEnum : return "MeltingOffset";
+		case MisfitEnum : return "Misfit";
+		case NumberNodeToElementConnectivityEnum : return "NumberNodeToElementConnectivity";
+		case PressureEnum : return "Pressure";
+		case PressurePicardEnum : return "PressurePicard";
+		case QmuPressureEnum : return "QmuPressure";
+		case QmuVxEnum : return "QmuVx";
+		case QmuVyEnum : return "QmuVy";
+		case QmuVzEnum : return "QmuVz";
+		case QmuThicknessEnum : return "QmuThickness";
+		case QmuBedEnum : return "QmuBed";
+		case QmuSurfaceEnum : return "QmuSurface";
+		case QmuMeltingEnum : return "QmuMelting";
+		case QmuVxMeshEnum : return "QmuVxMesh";
+		case QmuVyMeshEnum : return "QmuVyMesh";
+		case QmuVzMeshEnum : return "QmuVzMesh";
+		case AndroidFrictionCoefficientEnum : return "AndroidFrictionCoefficient";
+		case ResetPenaltiesEnum : return "ResetPenalties";
+		case SegmentOnIceShelfEnum : return "SegmentOnIceShelf";
+		case SurfaceAbsVelMisfitEnum : return "SurfaceAbsVelMisfit";
+		case SurfaceAreaEnum : return "SurfaceArea";
+		case SurfaceAverageVelMisfitEnum : return "SurfaceAverageVelMisfit";
+		case SurfaceLogVelMisfitEnum : return "SurfaceLogVelMisfit";
+		case SurfaceLogVxVyMisfitEnum : return "SurfaceLogVxVyMisfit";
+		case SurfaceRelVelMisfitEnum : return "SurfaceRelVelMisfit";
+		case SurfaceSlopeXEnum : return "SurfaceSlopeX";
+		case SurfaceSlopeYEnum : return "SurfaceSlopeY";
+		case TemperatureEnum : return "Temperature";
+		case TemperatureOldEnum : return "TemperatureOld";
+		case TemperaturePicardEnum : return "TemperaturePicard";
+		case ThicknessAbsMisfitEnum : return "ThicknessAbsMisfit";
+		case VelEnum : return "Vel";
+		case VelocityEnum : return "Velocity";
+		case VxAverageEnum : return "VxAverage";
+		case VxEnum : return "Vx";
+		case VxPicardEnum : return "VxPicard";
+		case VyAverageEnum : return "VyAverage";
+		case VyEnum : return "Vy";
+		case VyPicardEnum : return "VyPicard";
+		case VzEnum : return "Vz";
+		case VzMacAyealEnum : return "VzMacAyeal";
+		case VzPattynEnum : return "VzPattyn";
+		case VzPicardEnum : return "VzPicard";
+		case VzStokesEnum : return "VzStokes";
+		case VxMeshEnum : return "VxMesh";
+		case VyMeshEnum : return "VyMesh";
+		case VzMeshEnum : return "VzMesh";
+		case EnthalpyEnum : return "Enthalpy";
+		case EnthalpyPicardEnum : return "EnthalpyPicard";
+		case ThicknessAbsGradientEnum : return "ThicknessAbsGradient";
+		case ThicknessAlongGradientEnum : return "ThicknessAlongGradient";
+		case ThicknessAcrossGradientEnum : return "ThicknessAcrossGradient";
+		case StepResponsesEnum : return "StepResponses";
+		case IntMatParamEnum : return "IntMatParam";
+		case RheologyBbarAbsGradientEnum : return "RheologyBbarAbsGradient";
+		case DragCoefficientAbsGradientEnum : return "DragCoefficientAbsGradient";
+		case TransientInputEnum : return "TransientInput";
+		case WaterfractionEnum : return "Waterfraction";
+		case WatercolumnEnum : return "Watercolumn";
+		case BasalFrictionEnum : return "BasalFriction";
+		case ViscousHeatingEnum : return "ViscousHeating";
+		case QmuTemperatureEnum : return "QmuTemperature";
+		case HydrologyWaterVxEnum : return "HydrologyWaterVx";
+		case HydrologyWaterVyEnum : return "HydrologyWaterVy";
+		case StressTensorEnum : return "StressTensor";
+		case StressTensorxxEnum : return "StressTensorxx";
+		case StressTensorxyEnum : return "StressTensorxy";
+		case StressTensorxzEnum : return "StressTensorxz";
+		case StressTensoryyEnum : return "StressTensoryy";
+		case StressTensoryzEnum : return "StressTensoryz";
+		case StressTensorzzEnum : return "StressTensorzz";
+		case GiaCrossSectionShapeEnum : return "GiaCrossSectionShape";
+		case GiadWdtEnum : return "GiadWdt";
+		case GiaWEnum : return "GiaW";
+		case P0Enum : return "P0";
+		case P1Enum : return "P1";
+		case P1DGEnum : return "P1DG";
+		case MINIEnum : return "MINI";
+		case P2Enum : return "P2";
+		case SaveResultsEnum : return "SaveResults";
+		case BoolElementResultEnum : return "BoolElementResult";
+		case BoolExternalResultEnum : return "BoolExternalResult";
+		case DoubleElementResultEnum : return "DoubleElementResult";
+		case DoubleExternalResultEnum : return "DoubleExternalResult";
+		case DoubleMatExternalResultEnum : return "DoubleMatExternalResult";
+		case IntExternalResultEnum : return "IntExternalResult";
+		case JEnum : return "J";
+		case PatchEnum : return "Patch";
+		case PatchNodesEnum : return "PatchNodes";
+		case PatchVerticesEnum : return "PatchVertices";
+		case PentaP1ElementResultEnum : return "PentaP1ElementResult";
+		case StringExternalResultEnum : return "StringExternalResult";
+		case StepEnum : return "Step";
+		case TimeEnum : return "Time";
+		case TriaP1ElementResultEnum : return "TriaP1ElementResult";
+		case WaterColumnOldEnum : return "WaterColumnOld";
+		case MinVelEnum : return "MinVel";
+		case MaxVelEnum : return "MaxVel";
+		case MinVxEnum : return "MinVx";
+		case MaxVxEnum : return "MaxVx";
+		case MaxAbsVxEnum : return "MaxAbsVx";
+		case MinVyEnum : return "MinVy";
+		case MaxVyEnum : return "MaxVy";
+		case MaxAbsVyEnum : return "MaxAbsVy";
+		case MinVzEnum : return "MinVz";
+		case MaxVzEnum : return "MaxVz";
+		case MaxAbsVzEnum : return "MaxAbsVz";
+		case IceVolumeEnum : return "IceVolume";
+		case TotalSmbEnum : return "TotalSmb";
+		case AbsoluteEnum : return "Absolute";
+		case IncrementalEnum : return "Incremental";
+		case AgressiveMigrationEnum : return "AgressiveMigration";
+		case NoneEnum : return "None";
+		case SoftMigrationEnum : return "SoftMigration";
+		case SubelementMigrationEnum : return "SubelementMigration";
+		case SubelementMigration2Enum : return "SubelementMigration2";
+		case GLlevelsetEnum : return "GLlevelset";
+		case StokesSolverEnum : return "StokesSolver";
+		case AdjointEnum : return "Adjoint";
+		case ColinearEnum : return "Colinear";
+		case ControlSteadyEnum : return "ControlSteady";
+		case FsetEnum : return "Fset";
+		case Gradient1Enum : return "Gradient1";
+		case Gradient2Enum : return "Gradient2";
+		case Gradient3Enum : return "Gradient3";
+		case GradientEnum : return "Gradient";
+		case GroundinglineMigrationEnum : return "GroundinglineMigration";
+		case GsetEnum : return "Gset";
+		case IndexEnum : return "Index";
+		case IndexedEnum : return "Indexed";
+		case IntersectEnum : return "Intersect";
+		case NodalEnum : return "Nodal";
+		case OldGradientEnum : return "OldGradient";
+		case OutputFilePointerEnum : return "OutputFilePointer";
+		case OutputFileNameEnum : return "OutputFileName";
+		case LockFileNameEnum : return "LockFileName";
+		case ToolkitsOptionsAnalysesEnum : return "ToolkitsOptionsAnalyses";
+		case ToolkitsOptionsStringsEnum : return "ToolkitsOptionsStrings";
+		case QmuErrNameEnum : return "QmuErrName";
+		case QmuInNameEnum : return "QmuInName";
+		case QmuOutNameEnum : return "QmuOutName";
+		case RegularEnum : return "Regular";
+		case ScaledEnum : return "Scaled";
+		case SeparateEnum : return "Separate";
+		case SsetEnum : return "Sset";
+		case VerboseEnum : return "Verbose";
+		case TriangleInterpEnum : return "TriangleInterp";
+		case BilinearInterpEnum : return "BilinearInterp";
+		case NearestInterpEnum : return "NearestInterp";
+		case XYEnum : return "XY";
+		case XYZPEnum : return "XYZP";
+		case DenseEnum : return "Dense";
+		case MpiDenseEnum : return "MpiDense";
+		case SeqEnum : return "Seq";
+		case MpiEnum : return "Mpi";
+		case OptionEnum : return "Option";
+		case GenericOptionEnum : return "GenericOption";
+		case OptionCellEnum : return "OptionCell";
+		case OptionCharEnum : return "OptionChar";
+		case OptionStructEnum : return "OptionStruct";
+		case OptionDoubleEnum : return "OptionDouble";
+		case OptionLogicalEnum : return "OptionLogical";
+		case PatersonEnum : return "Paterson";
+		case ArrheniusEnum : return "Arrhenius";
+		default : return "unknown";
+
+	}
+}
+void EnumToStringx(char** pstring,int enum_in){
+	char *string = NULL;
+	int   len = 0;
+
+	len=strlen(EnumToStringx(enum_in));
+	string=xNew<char>(len+1);
+	memcpy(string,EnumToStringx(enum_in),(len+1)*sizeof(char));
+
+	/*Assign output pointer*/
+	*pstring=string;
+}
Index: /issm/trunk/src/c/shared/Enum/README
===================================================================
--- /issm/trunk/src/c/shared/Enum/README	(revision 15396)
+++ /issm/trunk/src/c/shared/Enum/README	(revision 15396)
@@ -0,0 +1,10 @@
+
+DO NOT MODIFY the following files:
+- StringToEnumx.cpp
+- EnumToStringx.cpp
+- src/m/enum/*
+all these files are automatically synchronized with EnumDefinitions.h
+
+TO ADD AN ENUM:
+add the corresponding lines to EnumDefinitions.h
+and execute synchronizing script.
Index: /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp
===================================================================
--- /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 15396)
+++ /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 15396)
@@ -0,0 +1,595 @@
+/*
+* \file StringToEnumx.cpp:
+* \brief: output enum associated with string
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include <cstring>
+#include "./Enum.h"
+#include "../Exceptions/exceptions.h"
+
+int  StringToEnumx(const char* name){
+
+   int  stage=1;
+
+   if(stage==1){
+	      if (strcmp(name,"AutodiffIsautodiff")==0) return AutodiffIsautodiffEnum;
+	      else if (strcmp(name,"AutodiffNumDependents")==0) return AutodiffNumDependentsEnum;
+	      else if (strcmp(name,"AutodiffNumDependentObjects")==0) return AutodiffNumDependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffDependentObjectNames")==0) return AutodiffDependentObjectNamesEnum;
+	      else if (strcmp(name,"AutodiffDependentObjectTypes")==0) return AutodiffDependentObjectTypesEnum;
+	      else if (strcmp(name,"AutodiffDependentObjectIndices")==0) return AutodiffDependentObjectIndicesEnum;
+	      else if (strcmp(name,"AutodiffDependentObjects")==0) return AutodiffDependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffNumIndependents")==0) return AutodiffNumIndependentsEnum;
+	      else if (strcmp(name,"AutodiffNumIndependentObjects")==0) return AutodiffNumIndependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffIndependentObjectNames")==0) return AutodiffIndependentObjectNamesEnum;
+	      else if (strcmp(name,"AutodiffIndependentObjectTypes")==0) return AutodiffIndependentObjectTypesEnum;
+	      else if (strcmp(name,"AutodiffIndependentObjects")==0) return AutodiffIndependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffJacobian")==0) return AutodiffJacobianEnum;
+	      else if (strcmp(name,"AutodiffXp")==0) return AutodiffXpEnum;
+	      else if (strcmp(name,"AutodiffDriver")==0) return AutodiffDriverEnum;
+	      else if (strcmp(name,"AutodiffFosForwardIndex")==0) return AutodiffFosForwardIndexEnum;
+	      else if (strcmp(name,"AutodiffFovForwardIndices")==0) return AutodiffFovForwardIndicesEnum;
+	      else if (strcmp(name,"AutodiffFosReverseIndex")==0) return AutodiffFosReverseIndexEnum;
+	      else if (strcmp(name,"AutodiffMassFluxSegmentsPresent")==0) return AutodiffMassFluxSegmentsPresentEnum;
+	      else if (strcmp(name,"AutodiffKeep")==0) return AutodiffKeepEnum;
+	      else if (strcmp(name,"BalancethicknessSpcthickness")==0) return BalancethicknessSpcthicknessEnum;
+	      else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
+	      else if (strcmp(name,"BalancethicknessThickeningRate")==0) return BalancethicknessThickeningRateEnum;
+	      else if (strcmp(name,"BasalforcingsGeothermalflux")==0) return BasalforcingsGeothermalfluxEnum;
+	      else if (strcmp(name,"BasalforcingsMeltingRateCorrection")==0) return BasalforcingsMeltingRateCorrectionEnum;
+	      else if (strcmp(name,"BasalforcingsMeltingRate")==0) return BasalforcingsMeltingRateEnum;
+	      else if (strcmp(name,"Bathymetry")==0) return BathymetryEnum;
+	      else if (strcmp(name,"Bed")==0) return BedEnum;
+	      else if (strcmp(name,"ConstantsG")==0) return ConstantsGEnum;
+	      else if (strcmp(name,"ConstantsReferencetemperature")==0) return ConstantsReferencetemperatureEnum;
+	      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,"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,"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,"FlowequationVertexEquation")==0) return FlowequationVertexEquationEnum;
+	      else if (strcmp(name,"FrictionCoefficient")==0) return FrictionCoefficientEnum;
+	      else if (strcmp(name,"FrictionP")==0) return FrictionPEnum;
+	      else if (strcmp(name,"FrictionQ")==0) return FrictionQEnum;
+	      else if (strcmp(name,"GeometryHydrostaticRatio")==0) return GeometryHydrostaticRatioEnum;
+	      else if (strcmp(name,"HydrologyModel")==0) return HydrologyModelEnum;
+	      else if (strcmp(name,"Hydrologyshreve")==0) return HydrologyshreveEnum;
+	      else if (strcmp(name,"HydrologyshreveCR")==0) return HydrologyshreveCREnum;
+	      else if (strcmp(name,"HydrologyshreveKn")==0) return HydrologyshreveKnEnum;
+	      else if (strcmp(name,"HydrologyshreveN")==0) return HydrologyshreveNEnum;
+	      else if (strcmp(name,"HydrologyshreveP")==0) return HydrologyshrevePEnum;
+	      else if (strcmp(name,"HydrologyshreveQ")==0) return HydrologyshreveQEnum;
+	      else if (strcmp(name,"HydrologyshreveSpcwatercolumn")==0) return HydrologyshreveSpcwatercolumnEnum;
+	      else if (strcmp(name,"HydrologyshreveStabilization")==0) return HydrologyshreveStabilizationEnum;
+	      else if (strcmp(name,"Hydrologydc")==0) return HydrologydcEnum;
+	      else if (strcmp(name,"SedimentHead")==0) return SedimentHeadEnum;
+	      else if (strcmp(name,"SedimentHeadOld")==0) return SedimentHeadOldEnum;
+	      else if (strcmp(name,"SedimentHeadResidual")==0) return SedimentHeadResidualEnum;
+	      else if (strcmp(name,"EplHead")==0) return EplHeadEnum;
+	      else if (strcmp(name,"EplHeadOld")==0) return EplHeadOldEnum;
+	      else if (strcmp(name,"HydrologydcRelTol")==0) return HydrologydcRelTolEnum;
+	      else if (strcmp(name,"HydrologydcSpcsedimentHead")==0) return HydrologydcSpcsedimentHeadEnum;
+	      else if (strcmp(name,"HydrologydcSedimentCompressibility")==0) return HydrologydcSedimentCompressibilityEnum;
+	      else if (strcmp(name,"HydrologydcSedimentPorosity")==0) return HydrologydcSedimentPorosityEnum;
+	      else if (strcmp(name,"HydrologydcSedimentThickness")==0) return HydrologydcSedimentThicknessEnum;
+	      else if (strcmp(name,"HydrologydcSedimentTransmitivity")==0) return HydrologydcSedimentTransmitivityEnum;
+	      else if (strcmp(name,"HydrologydcWaterCompressibility")==0) return HydrologydcWaterCompressibilityEnum;
+	      else if (strcmp(name,"HydrologydcSpceplHead")==0) return HydrologydcSpceplHeadEnum;
+	      else if (strcmp(name,"HydrologydcMaskEplactive")==0) return HydrologydcMaskEplactiveEnum;
+	      else if (strcmp(name,"HydrologydcEplCompressibility")==0) return HydrologydcEplCompressibilityEnum;
+	      else if (strcmp(name,"HydrologydcEplPorosity")==0) return HydrologydcEplPorosityEnum;
+	      else if (strcmp(name,"HydrologydcEplThickness")==0) return HydrologydcEplThicknessEnum;
+	      else if (strcmp(name,"HydrologydcEplTransmitivity")==0) return HydrologydcEplTransmitivityEnum;
+	      else if (strcmp(name,"HydrologydcIsefficientlayer")==0) return HydrologydcIsefficientlayerEnum;
+	      else if (strcmp(name,"HydrologydcSedimentlimitFlag")==0) return HydrologydcSedimentlimitFlagEnum;
+	      else if (strcmp(name,"HydrologydcSedimentlimit")==0) return HydrologydcSedimentlimitEnum;
+	      else if (strcmp(name,"HydrologydcTransferFlag")==0) return HydrologydcTransferFlagEnum;
+	      else if (strcmp(name,"HydrologydcLeakageFactor")==0) return HydrologydcLeakageFactorEnum;
+	      else if (strcmp(name,"HydrologydcPenaltyFactor")==0) return HydrologydcPenaltyFactorEnum;
+	      else if (strcmp(name,"HydrologyLayer")==0) return HydrologyLayerEnum;
+	      else if (strcmp(name,"HydrologySediment")==0) return HydrologySedimentEnum;
+	      else if (strcmp(name,"HydrologyEfficient")==0) return HydrologyEfficientEnum;
+	      else if (strcmp(name,"HydrologySedimentKmax")==0) return HydrologySedimentKmaxEnum;
+	      else if (strcmp(name,"BasisIntegral")==0) return BasisIntegralEnum;
+	      else if (strcmp(name,"WaterTransfer")==0) return WaterTransferEnum;
+	      else if (strcmp(name,"IndependentObject")==0) return IndependentObjectEnum;
+	      else if (strcmp(name,"InversionControlParameters")==0) return InversionControlParametersEnum;
+	      else if (strcmp(name,"InversionCostFunctionThreshold")==0) return InversionCostFunctionThresholdEnum;
+	      else if (strcmp(name,"InversionCostFunctionsCoefficients")==0) return InversionCostFunctionsCoefficientsEnum;
+	      else if (strcmp(name,"InversionCostFunctions")==0) return InversionCostFunctionsEnum;
+	      else if (strcmp(name,"InversionGradientOnly")==0) return InversionGradientOnlyEnum;
+	      else if (strcmp(name,"InversionGradientScaling")==0) return InversionGradientScalingEnum;
+	      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 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,"InversionNumControlParameters")==0) return InversionNumControlParametersEnum;
+	      else if (strcmp(name,"InversionNumCostFunctions")==0) return InversionNumCostFunctionsEnum;
+	      else if (strcmp(name,"InversionStepThreshold")==0) return InversionStepThresholdEnum;
+	      else if (strcmp(name,"InversionThicknessObs")==0) return InversionThicknessObsEnum;
+	      else if (strcmp(name,"InversionVelObs")==0) return InversionVelObsEnum;
+	      else if (strcmp(name,"InversionVxObs")==0) return InversionVxObsEnum;
+	      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,"MaterialsBeta")==0) return MaterialsBetaEnum;
+	      else if (strcmp(name,"MaterialsHeatcapacity")==0) return MaterialsHeatcapacityEnum;
+	      else if (strcmp(name,"MaterialsLatentheat")==0) return MaterialsLatentheatEnum;
+	      else if (strcmp(name,"MaterialsMeltingpoint")==0) return MaterialsMeltingpointEnum;
+	      else if (strcmp(name,"MaterialsMixedLayerCapacity")==0) return MaterialsMixedLayerCapacityEnum;
+	      else if (strcmp(name,"MaterialsRheologyB")==0) return MaterialsRheologyBEnum;
+	      else if (strcmp(name,"MaterialsRheologyBbar")==0) return MaterialsRheologyBbarEnum;
+	      else if (strcmp(name,"MaterialsRheologyLaw")==0) return MaterialsRheologyLawEnum;
+	      else if (strcmp(name,"MaterialsRheologyN")==0) return MaterialsRheologyNEnum;
+	      else if (strcmp(name,"MaterialsRheologyZ")==0) return MaterialsRheologyZEnum;
+	      else if (strcmp(name,"MaterialsRheologyZbar")==0) return MaterialsRheologyZbarEnum;
+	      else if (strcmp(name,"MaterialsRhoIce")==0) return MaterialsRhoIceEnum;
+	      else if (strcmp(name,"MaterialsRhoWater")==0) return MaterialsRhoWaterEnum;
+	      else if (strcmp(name,"MaterialsRhoFreshwater")==0) return MaterialsRhoFreshwaterEnum;
+	      else if (strcmp(name,"MaterialsMuWater")==0) return MaterialsMuWaterEnum;
+	      else if (strcmp(name,"MaterialsThermalExchangeVelocity")==0) return MaterialsThermalExchangeVelocityEnum;
+	      else if (strcmp(name,"MaterialsThermalconductivity")==0) return MaterialsThermalconductivityEnum;
+	      else if (strcmp(name,"MaterialsLithosphereShearModulus")==0) return MaterialsLithosphereShearModulusEnum;
+	      else if (strcmp(name,"MaterialsLithosphereDensity")==0) return MaterialsLithosphereDensityEnum;
+	      else if (strcmp(name,"MaterialsMantleShearModulus")==0) return MaterialsMantleShearModulusEnum;
+	      else if (strcmp(name,"MaterialsMantleDensity")==0) return MaterialsMantleDensityEnum;
+	      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;
+	      else if (strcmp(name,"MeshElements2d")==0) return MeshElements2dEnum;
+	      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;
+	      else if (strcmp(name,"MeshNumberoflayers")==0) return MeshNumberoflayersEnum;
+	      else if (strcmp(name,"MeshNumberofvertices2d")==0) return MeshNumberofvertices2dEnum;
+	      else if (strcmp(name,"MeshNumberofvertices")==0) return MeshNumberofverticesEnum;
+	      else if (strcmp(name,"MeshUpperelements")==0) return MeshUpperelementsEnum;
+	      else if (strcmp(name,"MeshVertexonbed")==0) return MeshVertexonbedEnum;
+	      else if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
+	      else if (strcmp(name,"MeshX")==0) return MeshXEnum;
+	      else if (strcmp(name,"MeshY")==0) return MeshYEnum;
+	      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,"QmuIsdakota")==0) return QmuIsdakotaEnum;
+	      else if (strcmp(name,"MassFluxSegments")==0) return MassFluxSegmentsEnum;
+	      else if (strcmp(name,"MassFluxSegmentsPresent")==0) return MassFluxSegmentsPresentEnum;
+	      else if (strcmp(name,"QmuMassFluxSegmentsPresent")==0) return QmuMassFluxSegmentsPresentEnum;
+	      else if (strcmp(name,"QmuNumberofpartitions")==0) return QmuNumberofpartitionsEnum;
+	      else if (strcmp(name,"QmuNumberofresponses")==0) return QmuNumberofresponsesEnum;
+	      else if (strcmp(name,"QmuPartition")==0) return QmuPartitionEnum;
+	      else if (strcmp(name,"QmuResponsedescriptors")==0) return QmuResponsedescriptorsEnum;
+	      else if (strcmp(name,"QmuVariabledescriptors")==0) return QmuVariabledescriptorsEnum;
+	      else if (strcmp(name,"QmuMaterialsRheologyB")==0) return QmuMaterialsRheologyBEnum;
+	      else if (strcmp(name,"RiftsNumrifts")==0) return RiftsNumriftsEnum;
+	      else if (strcmp(name,"RiftsRiftstruct")==0) return RiftsRiftstructEnum;
+	      else if (strcmp(name,"SettingsIoGather")==0) return SettingsIoGatherEnum;
+	      else if (strcmp(name,"SettingsLowmem")==0) return SettingsLowmemEnum;
+	      else if (strcmp(name,"SettingsOutputFrequency")==0) return SettingsOutputFrequencyEnum;
+	      else if (strcmp(name,"SettingsResultsAsPatches")==0) return SettingsResultsAsPatchesEnum;
+	      else if (strcmp(name,"SettingsWaitonlock")==0) return SettingsWaitonlockEnum;
+	      else if (strcmp(name,"SurfaceforcingsDelta18o")==0) return SurfaceforcingsDelta18oEnum;
+	      else if (strcmp(name,"SurfaceforcingsDelta18oSurface")==0) return SurfaceforcingsDelta18oSurfaceEnum;
+	      else if (strcmp(name,"SurfaceforcingsIsdelta18o")==0) return SurfaceforcingsIsdelta18oEnum;
+	      else if (strcmp(name,"SurfaceforcingsPrecipitationsPresentday")==0) return SurfaceforcingsPrecipitationsPresentdayEnum;
+	      else if (strcmp(name,"SurfaceforcingsTemperaturesPresentday")==0) return SurfaceforcingsTemperaturesPresentdayEnum;
+	      else if (strcmp(name,"SurfaceforcingsTemperaturesLgm")==0) return SurfaceforcingsTemperaturesLgmEnum;
+	      else if (strcmp(name,"DebugProfiling")==0) return DebugProfilingEnum;
+	      else if (strcmp(name,"ProfilingCurrentMem")==0) return ProfilingCurrentMemEnum;
+	      else if (strcmp(name,"ProfilingCurrentFlops")==0) return ProfilingCurrentFlopsEnum;
+	      else if (strcmp(name,"ProfilingSolutionTime")==0) return ProfilingSolutionTimeEnum;
+	      else if (strcmp(name,"MaxIterationConvergenceFlag")==0) return MaxIterationConvergenceFlagEnum;
+	      else if (strcmp(name,"SteadystateMaxiter")==0) return SteadystateMaxiterEnum;
+	      else if (strcmp(name,"SteadystateNumRequestedOutputs")==0) return SteadystateNumRequestedOutputsEnum;
+	      else if (strcmp(name,"SteadystateReltol")==0) return SteadystateReltolEnum;
+	      else if (strcmp(name,"SteadystateRequestedOutputs")==0) return SteadystateRequestedOutputsEnum;
+	      else if (strcmp(name,"Surface")==0) return SurfaceEnum;
+	      else if (strcmp(name,"SurfaceforcingsPrecipitation")==0) return SurfaceforcingsPrecipitationEnum;
+	      else if (strcmp(name,"SurfaceforcingsMassBalance")==0) return SurfaceforcingsMassBalanceEnum;
+	      else if (strcmp(name,"SurfaceforcingsIspdd")==0) return SurfaceforcingsIspddEnum;
+	      else if (strcmp(name,"SurfaceforcingsDesfac")==0) return SurfaceforcingsDesfacEnum;
+	      else if (strcmp(name,"SurfaceforcingsS0p")==0) return SurfaceforcingsS0pEnum;
+	      else if (strcmp(name,"SurfaceforcingsIssmbgradients")==0) return SurfaceforcingsIssmbgradientsEnum;
+	      else if (strcmp(name,"SurfaceforcingsMonthlytemperatures")==0) return SurfaceforcingsMonthlytemperaturesEnum;
+	      else if (strcmp(name,"SurfaceforcingsHref")==0) return SurfaceforcingsHrefEnum;
+	      else if (strcmp(name,"SurfaceforcingsSmbref")==0) return SurfaceforcingsSmbrefEnum;
+	      else if (strcmp(name,"SurfaceforcingsBPos")==0) return SurfaceforcingsBPosEnum;
+	      else if (strcmp(name,"SurfaceforcingsBNeg")==0) return SurfaceforcingsBNegEnum;
+	      else if (strcmp(name,"ThermalMaxiter")==0) return ThermalMaxiterEnum;
+	      else if (strcmp(name,"ThermalPenaltyFactor")==0) return ThermalPenaltyFactorEnum;
+	      else if (strcmp(name,"ThermalPenaltyLock")==0) return ThermalPenaltyLockEnum;
+	      else if (strcmp(name,"ThermalPenaltyThreshold")==0) return ThermalPenaltyThresholdEnum;
+	      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 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;
+	      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,"TransientIsgroundingline")==0) return TransientIsgroundinglineEnum;
+	      else if (strcmp(name,"TransientIsprognostic")==0) return TransientIsprognosticEnum;
+	      else if (strcmp(name,"TransientIsthermal")==0) return TransientIsthermalEnum;
+	      else if (strcmp(name,"TransientIsgia")==0) return TransientIsgiaEnum;
+	      else if (strcmp(name,"TransientNumRequestedOutputs")==0) return TransientNumRequestedOutputsEnum;
+	      else if (strcmp(name,"TransientRequestedOutputs")==0) return TransientRequestedOutputsEnum;
+	      else if (strcmp(name,"SolutionType")==0) return SolutionTypeEnum;
+	      else if (strcmp(name,"AnalysisType")==0) return AnalysisTypeEnum;
+	      else if (strcmp(name,"ConfigurationType")==0) return ConfigurationTypeEnum;
+	      else if (strcmp(name,"AdjointBalancethicknessAnalysis")==0) return AdjointBalancethicknessAnalysisEnum;
+	      else if (strcmp(name,"AdjointHorizAnalysis")==0) return AdjointHorizAnalysisEnum;
+	      else if (strcmp(name,"AdjointSolution")==0) return AdjointSolutionEnum;
+	      else if (strcmp(name,"AnalysisCounter")==0) return AnalysisCounterEnum;
+	      else if (strcmp(name,"NoneAnalysis")==0) return NoneAnalysisEnum;
+	      else if (strcmp(name,"DefaultAnalysis")==0) return DefaultAnalysisEnum;
+	      else if (strcmp(name,"BalancethicknessAnalysis")==0) return BalancethicknessAnalysisEnum;
+	      else if (strcmp(name,"BalancethicknessSolution")==0) return BalancethicknessSolutionEnum;
+	      else if (strcmp(name,"BalancethicknessSoftAnalysis")==0) return BalancethicknessSoftAnalysisEnum;
+	      else if (strcmp(name,"BalancethicknessSoftSolution")==0) return BalancethicknessSoftSolutionEnum;
+	      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,"EnthalpyAnalysis")==0) return EnthalpyAnalysisEnum;
+	      else if (strcmp(name,"EnthalpySolution")==0) return EnthalpySolutionEnum;
+	      else if (strcmp(name,"FlaimAnalysis")==0) return FlaimAnalysisEnum;
+	      else if (strcmp(name,"FlaimSolution")==0) return FlaimSolutionEnum;
+	      else if (strcmp(name,"HydrologyShreveAnalysis")==0) return HydrologyShreveAnalysisEnum;
+	      else if (strcmp(name,"HydrologyDCInefficientAnalysis")==0) return HydrologyDCInefficientAnalysisEnum;
+	      else if (strcmp(name,"HydrologyDCEfficientAnalysis")==0) return HydrologyDCEfficientAnalysisEnum;
+	      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,"SteadystateSolution")==0) return SteadystateSolutionEnum;
+	      else if (strcmp(name,"SurfaceSlopeAnalysis")==0) return SurfaceSlopeAnalysisEnum;
+	      else if (strcmp(name,"SurfaceSlopeSolution")==0) return SurfaceSlopeSolutionEnum;
+	      else if (strcmp(name,"SurfaceSlopeXAnalysis")==0) return SurfaceSlopeXAnalysisEnum;
+	      else if (strcmp(name,"SurfaceSlopeYAnalysis")==0) return SurfaceSlopeYAnalysisEnum;
+	      else if (strcmp(name,"ThermalAnalysis")==0) return ThermalAnalysisEnum;
+	      else if (strcmp(name,"ThermalSolution")==0) return ThermalSolutionEnum;
+	      else if (strcmp(name,"TransientSolution")==0) return TransientSolutionEnum;
+	      else if (strcmp(name,"GiaSolution")==0) return GiaSolutionEnum;
+	      else if (strcmp(name,"GiaAnalysis")==0) return GiaAnalysisEnum;
+	      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,"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,"Constraints")==0) return ConstraintsEnum;
+	      else if (strcmp(name,"Loads")==0) return LoadsEnum;
+	      else if (strcmp(name,"Materials")==0) return MaterialsEnum;
+	      else if (strcmp(name,"Nodes")==0) return NodesEnum;
+	      else if (strcmp(name,"Contours")==0) return ContoursEnum;
+	      else if (strcmp(name,"Parameters")==0) return ParametersEnum;
+	      else if (strcmp(name,"Vertices")==0) return VerticesEnum;
+	      else if (strcmp(name,"Results")==0) return ResultsEnum;
+	      else if (strcmp(name,"GenericParam")==0) return GenericParamEnum;
+	      else if (strcmp(name,"AdolcParam")==0) return AdolcParamEnum;
+	      else if (strcmp(name,"BoolInput")==0) return BoolInputEnum;
+	      else if (strcmp(name,"BoolParam")==0) return BoolParamEnum;
+	      else if (strcmp(name,"Contour")==0) return ContourEnum;
+	      else if (strcmp(name,"ControlInput")==0) return ControlInputEnum;
+	      else if (strcmp(name,"DatasetInput")==0) return DatasetInputEnum;
+	      else if (strcmp(name,"DofIndexing")==0) return DofIndexingEnum;
+	      else if (strcmp(name,"DoubleInput")==0) return DoubleInputEnum;
+	      else if (strcmp(name,"DataSetParam")==0) return DataSetParamEnum;
+	      else if (strcmp(name,"DoubleMatArrayParam")==0) return DoubleMatArrayParamEnum;
+	      else if (strcmp(name,"DoubleMatParam")==0) return DoubleMatParamEnum;
+	      else if (strcmp(name,"DoubleParam")==0) return DoubleParamEnum;
+	      else if (strcmp(name,"DoubleVecParam")==0) return DoubleVecParamEnum;
+	      else if (strcmp(name,"Element")==0) return ElementEnum;
+	      else if (strcmp(name,"ElementResult")==0) return ElementResultEnum;
+	      else if (strcmp(name,"ExternalResult")==0) return ExternalResultEnum;
+	      else if (strcmp(name,"FileParam")==0) return FileParamEnum;
+	      else if (strcmp(name,"Hook")==0) return HookEnum;
+	      else if (strcmp(name,"Icefront")==0) return IcefrontEnum;
+	      else if (strcmp(name,"Input")==0) return InputEnum;
+	      else if (strcmp(name,"IntInput")==0) return IntInputEnum;
+	      else if (strcmp(name,"IntParam")==0) return IntParamEnum;
+	      else if (strcmp(name,"IntVecParam")==0) return IntVecParamEnum;
+	      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,"Matice")==0) return MaticeEnum;
+	      else if (strcmp(name,"Matdamageice")==0) return MatdamageiceEnum;
+	      else if (strcmp(name,"Matpar")==0) return MatparEnum;
+	      else if (strcmp(name,"Node")==0) return NodeEnum;
+	      else if (strcmp(name,"Numericalflux")==0) return NumericalfluxEnum;
+	      else if (strcmp(name,"NumericalfluxType")==0) return NumericalfluxTypeEnum;
+	      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,"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,"Profiler")==0) return ProfilerEnum;
+	      else if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
+	      else if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
+	      else if (strcmp(name,"VectorParam")==0) return VectorParamEnum;
+	      else if (strcmp(name,"Riftfront")==0) return RiftfrontEnum;
+	      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,"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,"StringArrayParam")==0) return StringArrayParamEnum;
+	      else if (strcmp(name,"StringParam")==0) return StringParamEnum;
+	      else if (strcmp(name,"Tria")==0) return TriaEnum;
+	      else if (strcmp(name,"TriaInput")==0) return TriaInputEnum;
+	      else if (strcmp(name,"Vertex")==0) return VertexEnum;
+	      else if (strcmp(name,"VertexPId")==0) return VertexPIdEnum;
+	      else if (strcmp(name,"VertexSId")==0) return VertexSIdEnum;
+	      else if (strcmp(name,"Air")==0) return AirEnum;
+	      else if (strcmp(name,"Ice")==0) return IceEnum;
+	      else if (strcmp(name,"Melange")==0) return MelangeEnum;
+	      else if (strcmp(name,"Water")==0) return WaterEnum;
+	      else if (strcmp(name,"Closed")==0) return ClosedEnum;
+	      else if (strcmp(name,"Free")==0) return FreeEnum;
+	      else if (strcmp(name,"Open")==0) return OpenEnum;
+	      else if (strcmp(name,"Adjointp")==0) return AdjointpEnum;
+	      else if (strcmp(name,"Adjointx")==0) return AdjointxEnum;
+	      else if (strcmp(name,"Adjointy")==0) return AdjointyEnum;
+	      else if (strcmp(name,"Adjointz")==0) return AdjointzEnum;
+	      else if (strcmp(name,"BalancethicknessMisfit")==0) return BalancethicknessMisfitEnum;
+	      else if (strcmp(name,"BedSlopeX")==0) return BedSlopeXEnum;
+	      else if (strcmp(name,"BedSlopeY")==0) return BedSlopeYEnum;
+	      else if (strcmp(name,"Boundary")==0) return BoundaryEnum;
+	      else if (strcmp(name,"Constant")==0) return ConstantEnum;
+	      else if (strcmp(name,"Converged")==0) return ConvergedEnum;
+	      else if (strcmp(name,"Fill")==0) return FillEnum;
+	      else if (strcmp(name,"FractionIncrement")==0) return FractionIncrementEnum;
+	      else if (strcmp(name,"Friction")==0) return FrictionEnum;
+	      else if (strcmp(name,"GroundinglineMeltingRate")==0) return GroundinglineMeltingRateEnum;
+	      else if (strcmp(name,"Internal")==0) return InternalEnum;
+	      else if (strcmp(name,"MassFlux")==0) return MassFluxEnum;
+	      else if (strcmp(name,"MaxPenetration")==0) return MaxPenetrationEnum;
+	      else if (strcmp(name,"MeltingOffset")==0) return MeltingOffsetEnum;
+	      else if (strcmp(name,"Misfit")==0) return MisfitEnum;
+	      else if (strcmp(name,"NumberNodeToElementConnectivity")==0) return NumberNodeToElementConnectivityEnum;
+	      else if (strcmp(name,"Pressure")==0) return PressureEnum;
+	      else if (strcmp(name,"PressurePicard")==0) return PressurePicardEnum;
+	      else if (strcmp(name,"QmuPressure")==0) return QmuPressureEnum;
+	      else if (strcmp(name,"QmuVx")==0) return QmuVxEnum;
+	      else if (strcmp(name,"QmuVy")==0) return QmuVyEnum;
+	      else if (strcmp(name,"QmuVz")==0) return QmuVzEnum;
+	      else if (strcmp(name,"QmuThickness")==0) return QmuThicknessEnum;
+	      else if (strcmp(name,"QmuBed")==0) return QmuBedEnum;
+	      else if (strcmp(name,"QmuSurface")==0) return QmuSurfaceEnum;
+	      else if (strcmp(name,"QmuMelting")==0) return QmuMeltingEnum;
+	      else if (strcmp(name,"QmuVxMesh")==0) return QmuVxMeshEnum;
+	      else if (strcmp(name,"QmuVyMesh")==0) return QmuVyMeshEnum;
+	      else if (strcmp(name,"QmuVzMesh")==0) return QmuVzMeshEnum;
+	      else if (strcmp(name,"AndroidFrictionCoefficient")==0) return AndroidFrictionCoefficientEnum;
+	      else if (strcmp(name,"ResetPenalties")==0) return ResetPenaltiesEnum;
+	      else if (strcmp(name,"SegmentOnIceShelf")==0) return SegmentOnIceShelfEnum;
+	      else if (strcmp(name,"SurfaceAbsVelMisfit")==0) return SurfaceAbsVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceArea")==0) return SurfaceAreaEnum;
+	      else if (strcmp(name,"SurfaceAverageVelMisfit")==0) return SurfaceAverageVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceLogVelMisfit")==0) return SurfaceLogVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceLogVxVyMisfit")==0) return SurfaceLogVxVyMisfitEnum;
+	      else if (strcmp(name,"SurfaceRelVelMisfit")==0) return SurfaceRelVelMisfitEnum;
+	      else if (strcmp(name,"SurfaceSlopeX")==0) return SurfaceSlopeXEnum;
+	      else if (strcmp(name,"SurfaceSlopeY")==0) return SurfaceSlopeYEnum;
+	      else if (strcmp(name,"Temperature")==0) return TemperatureEnum;
+	      else if (strcmp(name,"TemperatureOld")==0) return TemperatureOldEnum;
+	      else if (strcmp(name,"TemperaturePicard")==0) return TemperaturePicardEnum;
+	      else if (strcmp(name,"ThicknessAbsMisfit")==0) return ThicknessAbsMisfitEnum;
+	      else if (strcmp(name,"Vel")==0) return VelEnum;
+	      else if (strcmp(name,"Velocity")==0) return VelocityEnum;
+	      else if (strcmp(name,"VxAverage")==0) return VxAverageEnum;
+	      else if (strcmp(name,"Vx")==0) return VxEnum;
+	      else if (strcmp(name,"VxPicard")==0) return VxPicardEnum;
+	      else if (strcmp(name,"VyAverage")==0) return VyAverageEnum;
+	      else if (strcmp(name,"Vy")==0) return VyEnum;
+	      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,"VzPicard")==0) return VzPicardEnum;
+	      else if (strcmp(name,"VzStokes")==0) return VzStokesEnum;
+	      else if (strcmp(name,"VxMesh")==0) return VxMeshEnum;
+	      else if (strcmp(name,"VyMesh")==0) return VyMeshEnum;
+	      else if (strcmp(name,"VzMesh")==0) return VzMeshEnum;
+	      else if (strcmp(name,"Enthalpy")==0) return EnthalpyEnum;
+	      else if (strcmp(name,"EnthalpyPicard")==0) return EnthalpyPicardEnum;
+	      else if (strcmp(name,"ThicknessAbsGradient")==0) return ThicknessAbsGradientEnum;
+	      else if (strcmp(name,"ThicknessAlongGradient")==0) return ThicknessAlongGradientEnum;
+	      else if (strcmp(name,"ThicknessAcrossGradient")==0) return ThicknessAcrossGradientEnum;
+	      else if (strcmp(name,"StepResponses")==0) return StepResponsesEnum;
+	      else if (strcmp(name,"IntMatParam")==0) return IntMatParamEnum;
+	      else if (strcmp(name,"RheologyBbarAbsGradient")==0) return RheologyBbarAbsGradientEnum;
+	      else if (strcmp(name,"DragCoefficientAbsGradient")==0) return DragCoefficientAbsGradientEnum;
+	      else if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
+	      else if (strcmp(name,"Waterfraction")==0) return WaterfractionEnum;
+	      else if (strcmp(name,"Watercolumn")==0) return WatercolumnEnum;
+	      else if (strcmp(name,"BasalFriction")==0) return BasalFrictionEnum;
+	      else if (strcmp(name,"ViscousHeating")==0) return ViscousHeatingEnum;
+	      else if (strcmp(name,"QmuTemperature")==0) return QmuTemperatureEnum;
+	      else if (strcmp(name,"HydrologyWaterVx")==0) return HydrologyWaterVxEnum;
+	      else if (strcmp(name,"HydrologyWaterVy")==0) return HydrologyWaterVyEnum;
+	      else if (strcmp(name,"StressTensor")==0) return StressTensorEnum;
+	      else if (strcmp(name,"StressTensorxx")==0) return StressTensorxxEnum;
+	      else if (strcmp(name,"StressTensorxy")==0) return StressTensorxyEnum;
+	      else if (strcmp(name,"StressTensorxz")==0) return StressTensorxzEnum;
+	      else if (strcmp(name,"StressTensoryy")==0) return StressTensoryyEnum;
+	      else if (strcmp(name,"StressTensoryz")==0) return StressTensoryzEnum;
+	      else if (strcmp(name,"StressTensorzz")==0) return StressTensorzzEnum;
+	      else if (strcmp(name,"GiaCrossSectionShape")==0) return GiaCrossSectionShapeEnum;
+	      else if (strcmp(name,"GiadWdt")==0) return GiadWdtEnum;
+	      else if (strcmp(name,"GiaW")==0) return GiaWEnum;
+	      else if (strcmp(name,"P0")==0) return P0Enum;
+	      else if (strcmp(name,"P1")==0) return P1Enum;
+	      else if (strcmp(name,"P1DG")==0) return P1DGEnum;
+	      else if (strcmp(name,"MINI")==0) return MINIEnum;
+	      else if (strcmp(name,"P2")==0) return P2Enum;
+	      else if (strcmp(name,"SaveResults")==0) return SaveResultsEnum;
+	      else if (strcmp(name,"BoolElementResult")==0) return BoolElementResultEnum;
+	      else if (strcmp(name,"BoolExternalResult")==0) return BoolExternalResultEnum;
+	      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,"IntExternalResult")==0) return IntExternalResultEnum;
+	      else if (strcmp(name,"J")==0) return JEnum;
+	      else if (strcmp(name,"Patch")==0) return PatchEnum;
+	      else if (strcmp(name,"PatchNodes")==0) return PatchNodesEnum;
+	      else if (strcmp(name,"PatchVertices")==0) return PatchVerticesEnum;
+	      else if (strcmp(name,"PentaP1ElementResult")==0) return PentaP1ElementResultEnum;
+	      else if (strcmp(name,"StringExternalResult")==0) return StringExternalResultEnum;
+	      else if (strcmp(name,"Step")==0) return StepEnum;
+	      else if (strcmp(name,"Time")==0) return TimeEnum;
+	      else if (strcmp(name,"TriaP1ElementResult")==0) return TriaP1ElementResultEnum;
+	      else if (strcmp(name,"WaterColumnOld")==0) return WaterColumnOldEnum;
+	      else if (strcmp(name,"MinVel")==0) return MinVelEnum;
+	      else if (strcmp(name,"MaxVel")==0) return MaxVelEnum;
+	      else if (strcmp(name,"MinVx")==0) return MinVxEnum;
+	      else if (strcmp(name,"MaxVx")==0) return MaxVxEnum;
+	      else if (strcmp(name,"MaxAbsVx")==0) return MaxAbsVxEnum;
+	      else if (strcmp(name,"MinVy")==0) return MinVyEnum;
+	      else if (strcmp(name,"MaxVy")==0) return MaxVyEnum;
+	      else if (strcmp(name,"MaxAbsVy")==0) return MaxAbsVyEnum;
+	      else if (strcmp(name,"MinVz")==0) return MinVzEnum;
+	      else if (strcmp(name,"MaxVz")==0) return MaxVzEnum;
+	      else if (strcmp(name,"MaxAbsVz")==0) return MaxAbsVzEnum;
+	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
+	      else if (strcmp(name,"TotalSmb")==0) return TotalSmbEnum;
+	      else if (strcmp(name,"Absolute")==0) return AbsoluteEnum;
+	      else if (strcmp(name,"Incremental")==0) return IncrementalEnum;
+	      else if (strcmp(name,"AgressiveMigration")==0) return AgressiveMigrationEnum;
+	      else if (strcmp(name,"None")==0) return NoneEnum;
+	      else if (strcmp(name,"SoftMigration")==0) return SoftMigrationEnum;
+	      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,"Adjoint")==0) return AdjointEnum;
+	      else if (strcmp(name,"Colinear")==0) return ColinearEnum;
+	      else if (strcmp(name,"ControlSteady")==0) return ControlSteadyEnum;
+	      else if (strcmp(name,"Fset")==0) return FsetEnum;
+	      else if (strcmp(name,"Gradient1")==0) return Gradient1Enum;
+	      else if (strcmp(name,"Gradient2")==0) return Gradient2Enum;
+	      else if (strcmp(name,"Gradient3")==0) return Gradient3Enum;
+	      else if (strcmp(name,"Gradient")==0) return GradientEnum;
+	      else if (strcmp(name,"GroundinglineMigration")==0) return GroundinglineMigrationEnum;
+	      else if (strcmp(name,"Gset")==0) return GsetEnum;
+	      else if (strcmp(name,"Index")==0) return IndexEnum;
+	      else if (strcmp(name,"Indexed")==0) return IndexedEnum;
+	      else if (strcmp(name,"Intersect")==0) return IntersectEnum;
+	      else if (strcmp(name,"Nodal")==0) return NodalEnum;
+	      else if (strcmp(name,"OldGradient")==0) return OldGradientEnum;
+	      else if (strcmp(name,"OutputFilePointer")==0) return OutputFilePointerEnum;
+	      else if (strcmp(name,"OutputFileName")==0) return OutputFileNameEnum;
+	      else if (strcmp(name,"LockFileName")==0) return LockFileNameEnum;
+	      else if (strcmp(name,"ToolkitsOptionsAnalyses")==0) return ToolkitsOptionsAnalysesEnum;
+	      else if (strcmp(name,"ToolkitsOptionsStrings")==0) return ToolkitsOptionsStringsEnum;
+	      else if (strcmp(name,"QmuErrName")==0) return QmuErrNameEnum;
+	      else if (strcmp(name,"QmuInName")==0) return QmuInNameEnum;
+	      else if (strcmp(name,"QmuOutName")==0) return QmuOutNameEnum;
+	      else if (strcmp(name,"Regular")==0) return RegularEnum;
+	      else if (strcmp(name,"Scaled")==0) return ScaledEnum;
+	      else if (strcmp(name,"Separate")==0) return SeparateEnum;
+	      else if (strcmp(name,"Sset")==0) return SsetEnum;
+	      else if (strcmp(name,"Verbose")==0) return VerboseEnum;
+	      else if (strcmp(name,"TriangleInterp")==0) return TriangleInterpEnum;
+	      else if (strcmp(name,"BilinearInterp")==0) return BilinearInterpEnum;
+	      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,"Dense")==0) return DenseEnum;
+	      else if (strcmp(name,"MpiDense")==0) return MpiDenseEnum;
+	      else if (strcmp(name,"Seq")==0) return SeqEnum;
+	      else if (strcmp(name,"Mpi")==0) return MpiEnum;
+	      else if (strcmp(name,"Option")==0) return OptionEnum;
+	      else if (strcmp(name,"GenericOption")==0) return GenericOptionEnum;
+	      else if (strcmp(name,"OptionCell")==0) return OptionCellEnum;
+	      else if (strcmp(name,"OptionChar")==0) return OptionCharEnum;
+	      else if (strcmp(name,"OptionStruct")==0) return OptionStructEnum;
+	      else if (strcmp(name,"OptionDouble")==0) return OptionDoubleEnum;
+	      else if (strcmp(name,"OptionLogical")==0) return OptionLogicalEnum;
+	      else if (strcmp(name,"Paterson")==0) return PatersonEnum;
+	      else if (strcmp(name,"Arrhenius")==0) return ArrheniusEnum;
+         else stage=6;
+   }
+	/*If we reach this point, the string provided has not been found*/
+	_error_("Enum " << name << " not found");
+}
Index: /issm/trunk/src/c/shared/Enum/Synchronize.sh
===================================================================
--- /issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 15396)
+++ /issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 15396)
@@ -0,0 +1,223 @@
+#!/bin/bash
+#Synchronize EnumToStringx.cpp and StringToEnumx.cpp and matlab Enums
+
+#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
+
+#Removed existing files
+rm $ISSM_DIR/src/m/enum/*.m
+rm $ISSM_DIR/src/m/enum/*.py
+rm $ISSM_DIR/src/c/shared/Enum/EnumToStringx.cpp
+rm $ISSM_DIR/src/c/shared/Enum/StringToEnumx.cpp
+
+#Get number of enums
+NUMENUMS=$(wc -l temp | awk '{printf("%s",$1);}');
+
+#Build EnumToStringx.cpp {{{
+#Header
+cat <<END >  $ISSM_DIR/src/c/shared/Enum/EnumToStringx.cpp
+/*
+* \file EnumToStringx.cpp:
+* \brief: output string associated with enum
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include <cstring>
+#include "./Enum.h"
+#include "../Exceptions/exceptions.h"
+#include "../MemOps/MemOps.h"
+
+const char* EnumToStringx(int en){
+
+	switch(en){
+
+END
+#core
+cat temp |  awk '{print "\t\t" "case " $1" : return \"" substr($1,1,length($1)-4) "\";"}' >> $ISSM_DIR/src/c/shared/Enum/EnumToStringx.cpp
+#Footer
+cat <<END >> $ISSM_DIR/src/c/shared/Enum/EnumToStringx.cpp
+		default : return "unknown";
+
+	}
+}
+void EnumToStringx(char** pstring,int enum_in){
+	char *string = NULL;
+	int   len = 0;
+
+	len=strlen(EnumToStringx(enum_in));
+	string=xNew<char>(len+1);
+	memcpy(string,EnumToStringx(enum_in),(len+1)*sizeof(char));
+
+	/*Assign output pointer*/
+	*pstring=string;
+}
+END
+#}}}
+#Build StringToEnumx.cpp {{{
+#Header
+cat <<END > $ISSM_DIR/src/c/shared/Enum/StringToEnumx.cpp
+/*
+* \file StringToEnumx.cpp:
+* \brief: output enum associated with string
+*
+*   WARNING: DO NOT MODIFY THIS FILE
+*            this file has been automatically generated by Synchronize.sh
+*            Please read README for more information
+*/
+
+#include <cstring>
+#include "./Enum.h"
+#include "../Exceptions/exceptions.h"
+
+int  StringToEnumx(const char* name){
+
+   int  stage=1;
+
+END
+
+#core
+i1=1;
+i2=120;
+for (( i=1 ; i<=100 ; i++ )); do
+	echo "   if(stage==$i){" >> $ISSM_DIR//src/c/shared/Enum/StringToEnumx.cpp
+	awk -v i1=$i1 -v i2=$i2 '{if(NR>=i1 && NR<=i2) print $0 }' temp |
+	awk '{print "\t" ((NR==1)?"      if":"      else if") " (strcmp(name,\"" substr($1,1,length($1)-4) "\")==0) return " $1 ";"}' >> $ISSM_DIR//src/c/shared/Enum/StringToEnumx.cpp
+	echo "         else stage=$(($i+1));" >> $ISSM_DIR//src/c/shared/Enum/StringToEnumx.cpp
+	echo "   }" >> $ISSM_DIR//src/c/shared/Enum/StringToEnumx.cpp
+	
+	if [ $i2 -ge $NUMENUMS ]; then break; fi
+	let i1=$i1+120
+	let i2=$i2+120
+done
+
+#footer
+cat <<END >> $ISSM_DIR/src/c/shared/Enum/StringToEnumx.cpp
+	/*If we reach this point, the string provided has not been found*/
+	_error_("Enum " << name << " not found");
+}
+END
+#}}}
+
+# go through the lines of temp
+ENUM=0;
+#Add header to pythonenum file{{{
+cat <<END > $ISSM_DIR/src/m/enum/EnumDefinitions.py
+from StringToEnum import StringToEnum
+
+"""
+
+   WARNING: DO NOT MODIFY THIS 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
+#}}}
+
+for NAMEENUM in $(cat temp); do
+
+	#Get name and enum of the line i
+	NAME=$(echo $NAMEENUM | sed -e "s/Enum//g")
+	#offset Enum by one (Enum begins with 0 and not 1!)
+	let ENUM=$ENUM+1
+
+	#print info {{{
+	if [ $ENUM -lt 10 ]
+	then
+		printf "\r                                                                      "
+		printf "\r  $ENUM/$NUMENUMS Adding "$NAME"..."
+	else
+		if [ $ENUM -lt 100 ]
+		then
+			printf "\r                                                                      "
+			printf "\r $ENUM/$NUMENUMS Adding "$NAME"..."
+		else
+			printf "\r                                                                      "
+			printf "\r$ENUM/$NUMENUMS Adding "$NAME"..."
+		fi
+	fi
+	#}}}
+	#Add case to matlabenum file{{{
+	cat <<END > $ISSM_DIR"/src/m/enum/"$(echo $NAMEENUM".m")
+function macro=$(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()
+
+macro=StringToEnum('$NAME');
+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
+#}}}
+#print info {{{
+printf "\r                                                                      "
+printf "\rdone!\n"
+#}}}
Index: /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp	(revision 15396)
@@ -9,6 +9,7 @@
 #endif
 
-#include "../shared.h"
-#include "../../include/include.h"
+#include "./exceptions.h"
+#include "../io/Print/Print.h"
+#include "../io/Comm/Comm.h"
 
 ErrorException::ErrorException(const string &what_arg){/*{{{*/
@@ -41,14 +42,14 @@
 
 	if (function_name=="" || file_line==0){ //WINDOWS
-		_printString_("Error message: " << what());
+		_printf_("Error message: " << what());
 	}
 	else{
 		if(num_procs==1){
-			_printLine_("\n??? Error in ==> " << file_name.c_str() << ":" << file_line);
-			_printLine_(function_name.c_str() << " error message: " << what() << "\n");
+			_printf_("\n??? Error in ==> " << file_name.c_str() << ":" << file_line << "\n");
+			_printf_(function_name.c_str() << " error message: " << what() << "\n\n");
 		}
 		else{
-			_printLine_("\n[" << my_rank<< "] ??? Error using ==> " << file_name.c_str() << ":" << file_line);
-			_printLine_(  "[" << my_rank << "] " << function_name.c_str() << " error message: " << what() << "\n");
+			_printf_("\n[" << my_rank<< "] ??? Error using ==> " << file_name.c_str() << ":" << file_line << "\n");
+			_printf_(  "[" << my_rank << "] " << function_name.c_str() << " error message: " << what() << "\n\n");
 		}
 	}
Index: /issm/trunk/src/c/shared/Exceptions/exceptions.h
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/exceptions.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Exceptions/exceptions.h	(revision 15396)
@@ -7,13 +7,72 @@
  */
 
-#ifndef MY_EXCEPTIONS_H_
-#define MY_EXCEPTIONS_H_
+#ifndef _MY_EXCEPTIONS_H_
+#define _MY_EXCEPTIONS_H_
 
 #include <exception>
 #include <string>
+#include <iostream>
+#include <sstream>
+#include <iomanip>
+
 using namespace std;
 
-/*We derive our classes from the c++ exception class: */
-class ErrorException: public exception {
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*macros: */
+/* _assert_ {{{*/
+/*Assertion macro: do nothing if macro _ISSM_DEBUG_ undefined*/
+#ifdef _ISSM_DEBUG_ 
+#define _assert_(statement)\
+  if (!(statement)) _error_("Assertion \""<<#statement<<"\" failed, please report bug to "<<PACKAGE_BUGREPORT)
+#else
+#define _assert_(ignore)\
+  ((void) 0)
+#endif
+/*}}}*/
+/* _error_ {{{*/
+/*new Error exception macro*/
+#ifdef _INTEL_WIN_
+#define _error_(StreamArgs)\
+   do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+   aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
+   throw ErrorException(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+#else
+#define _error_(StreamArgs)\
+	do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+   aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
+   throw ErrorException(__FILE__,__func__,__LINE__,aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+#endif
+/*}}}*/
+/* ExceptionTrapBegin/ExceptionTrapEnd {{{*/
+
+/*The following macros hide the error exception handling in a matlab module. Just put 
+ * ExceptionTrapBegin(); and ExceptionTrapEnd(); at the beginning and end of a module, and c++ exceptions 
+ * will be trapped. Really nifty!*/
+
+#define ExceptionTrapBegin(); \
+	try{
+
+#define ExceptionTrapEnd(); }\
+	catch(ErrorException &exception){\
+		exception.Report();\
+		return 0;\
+	}\
+	catch (exception& e) {\
+		_printf_("Standard exception: " << e.what() << "\n\n");\
+		return 0;\
+	}\
+	catch(...){\
+		_printf_("An unexpected error occurred \n\n");\
+		return 0;\
+	}
+/*}}}*/
+
+/*ISSM exception class: */
+class ErrorException: public exception { /*{{{*/
 
 	string   what_str;
@@ -32,5 +91,7 @@
 
 };
+/*}}}*/
 
 char* exprintf(const char* format,...);
+
 #endif
Index: /issm/trunk/src/c/shared/Exceptions/exprintf.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/exprintf.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Exceptions/exprintf.cpp	(revision 15396)
@@ -8,6 +8,5 @@
 #include <stdarg.h>
 #include <stdio.h>
-#include "../Alloc/xNewDelete.h"
-#include "../Alloc/alloc.h"
+#include "../MemOps/MemOps.h"
 
 char* exprintf(const char* format,...){
Index: sm/trunk/src/c/shared/Exp/ExpWrite.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/ExpWrite.cpp	(revision 15395)
+++ 	(revision )
@@ -1,77 +1,0 @@
-/*!\file:  Exp.cpp
- * \brief Exp.cpp: write the vertex coordinates defined in a domain 
- * outline from Argus (.exp file). The first contour in the file is for 
- * the outside domain outline. 
- */
-#include <stdio.h>
-#include "../Alloc/alloc.h"
-#include "../../include/include.h"
-#include "../Exceptions/exceptions.h"
-#include "../../Container/DataSet.h"
-#include "../../classes/objects/Contour.h"
-
-int ExpWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,char* domainname){/*{{{*/
-
-	/*I/O: */
-	FILE* fid=NULL;
-
-	/*open domain outline file for writing: */
-	if((fid=fopen(domainname,"w"))==NULL) _error_("could not open domain file " << domainname); 
-
-	/*Start writing profiles: */
-	for(int counter=0;counter<nprof;counter++){
-
-		/*Write header: */
-		fprintf(fid,"## Name:%s\n",domainname);
-		fprintf(fid,"## Icon:0\n");
-		fprintf(fid,"# Points Count	Value\n");
-		fprintf(fid,"%u %s\n",profnvertices[counter]  ,"1.");
-		fprintf(fid,"# X pos	Y pos\n");
-
-		/*Write vertices: */
-		for(int i=0;i<profnvertices[counter];i++){
-			fprintf(fid,"%lf\t%lf\n",pprofx[counter][i],pprofy[counter][i]);
-		}
-
-		/*Write blank line: */
-		if(counter<nprof-1) fprintf(fid,"\n");
-	}
-
-	/*close Exp file: */
-	fclose(fid);
-
-	return 1;
-}/*}}}*/
-int ExpWrite(DataSet* contours,char* domainname){/*{{{*/
-
-	/*I/O: */
-	FILE* fid=NULL;
-	Contour<double>* contour = NULL;
-
-	/*open domain outline file for writing: */
-	if((fid=fopen(domainname,"w"))==NULL) _error_("could not open domain file " << domainname); 
-
-	for(int counter=0;counter<contours->Size();counter++){
-		contour=(Contour<double>*)contours->GetObjectByOffset(counter);
-
-		/*Write header: */
-		fprintf(fid,"## Name:%s\n",domainname);
-		fprintf(fid,"## Icon:0\n");
-		fprintf(fid,"# Points Count	Value\n");
-		fprintf(fid,"%u %s\n",contour->nods  ,"1.");
-		fprintf(fid,"# X pos	Y pos\n");
-
-		/*Write vertices: */
-		for(int i=0;i<contour->nods;i++){
-			fprintf(fid,"%lf\t%lf\n",contour->x[i],contour->y[i]);
-		}
-
-		/*Write blank line: */
-		if(counter<contours->Size()-1) fprintf(fid,"\n");
-	}
-
-	/*close Exp file: */
-	fclose(fid);
-
-	return 1;
-}/*}}}*/
Index: sm/trunk/src/c/shared/Exp/IsInPoly.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/IsInPoly.cpp	(revision 15395)
+++ 	(revision )
@@ -1,46 +1,0 @@
-/*!\file IsInPoly.c
- * \brief:  from a contour, determine which nodes are in  domain.
- */
-
-#include <math.h>
-#include "../../toolkits/toolkits.h"
-#include "./exp.h"
-#include "../shared.h"
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-/*pnpoly{{{*/
-int pnpoly(int npol, double *xp, double *yp, double x, double y, int edgevalue) {
-	int i, j, c = 0;
-	double n1, n2, normp, scalar;
-
-	/*first test, are they colinear? if yes, is the point in the middle of the segment*/
-	if (edgevalue != 2 ){
-		for (i = 0, j = npol-1; i < npol; j = i++) {
-			n1=pow(yp[i]-yp[j],2.0)+pow(xp[i]-xp[j],2.0);
-			n2=pow(y-yp[j],2.0)+pow(x-xp[j],2.0);
-			normp=pow(n1*n2,0.5);
-			scalar=(yp[i]-yp[j])*(y-yp[j])+(xp[i]-xp[j])*(x-xp[j]);
-
-			if (scalar == normp){
-				if (n2<=n1){
-					c = edgevalue;
-					return c;
-				}
-			}
-		}
-	}
-	/*second test : point is neither on a vertex, nor on a side, where is it ?*/
-	for (i = 0, j = npol-1; i < npol; j = i++) {
-		if ((((yp[i]<=y) && (y<yp[j])) ||
-					((yp[j]<=y) && (y<yp[i]))) &&
-				(x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i])){
-			c = !c;
-		}
-	}
-	return c;
-}/*}}}*/
Index: sm/trunk/src/c/shared/Exp/IsInPolySerial.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/IsInPolySerial.cpp	(revision 15395)
+++ 	(revision )
@@ -1,31 +1,0 @@
-/*
- * IsInPolySerial.c:
- */
-
-#include <math.h>
-
-#include "./exp.h"
-
-int IsInPolySerial(double* in,double* xc,double* yc,int numvertices,double* x,double* y,int nods, int edgevalue){
-
-	double x0,y0;
-
-	/*Go through all vertices of the mesh:*/
-	for(int i=0;i<nods;i++){
-		if (in[i]){
-			/*this vertex already is inside one of the contours, continue*/
-			continue;
-		}
-		/*pick up vertex: */
-		x0=x[i];
-		y0=y[i];
-		if (pnpoly(numvertices,xc,yc,x0,y0,edgevalue)){
-			in[i]=1.;
-		}
-		else{
-			in[i]=0.;
-		}
-	}
-
-	return 1;
-}
Index: /issm/trunk/src/c/shared/Exp/exp.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/exp.cpp	(revision 15396)
+++ /issm/trunk/src/c/shared/Exp/exp.cpp	(revision 15396)
@@ -0,0 +1,99 @@
+/*!\file:  Exp.cpp
+ * \brief Exp.cpp: write the vertex coordinates defined in a domain 
+ * outline from Argus (.exp file). The first contour in the file is for 
+ * the outside domain outline. 
+ */
+#include <stdio.h>
+#include <math.h>
+
+#include "../MemOps/MemOps.h"
+#include "../Exceptions/exceptions.h"
+#include "./exp.h"
+
+int ExpWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,char* domainname){/*{{{*/
+
+	/*I/O: */
+	FILE* fid=NULL;
+
+	/*open domain outline file for writing: */
+	if((fid=fopen(domainname,"w"))==NULL) _error_("could not open domain file " << domainname); 
+
+	/*Start writing profiles: */
+	for(int counter=0;counter<nprof;counter++){
+
+		/*Write header: */
+		fprintf(fid,"## Name:%s\n",domainname);
+		fprintf(fid,"## Icon:0\n");
+		fprintf(fid,"# Points Count	Value\n");
+		fprintf(fid,"%u %s\n",profnvertices[counter]  ,"1.");
+		fprintf(fid,"# X pos	Y pos\n");
+
+		/*Write vertices: */
+		for(int i=0;i<profnvertices[counter];i++){
+			fprintf(fid,"%lf\t%lf\n",pprofx[counter][i],pprofy[counter][i]);
+		}
+
+		/*Write blank line: */
+		if(counter<nprof-1) fprintf(fid,"\n");
+	}
+
+	/*close Exp file: */
+	fclose(fid);
+
+	return 1;
+}/*}}}*/
+int IsInPolySerial(double* in,double* xc,double* yc,int numvertices,double* x,double* y,int nods, int edgevalue){ /*{{{*/
+
+	double x0,y0;
+
+	/*Go through all vertices of the mesh:*/
+	for(int i=0;i<nods;i++){
+		if (in[i]){
+			/*this vertex already is inside one of the contours, continue*/
+			continue;
+		}
+		/*pick up vertex: */
+		x0=x[i];
+		y0=y[i];
+		if (pnpoly(numvertices,xc,yc,x0,y0,edgevalue)){
+			in[i]=1.;
+		}
+		else{
+			in[i]=0.;
+		}
+	}
+
+	return 1;
+}
+/*}}}*/
+/*pnpoly{{{*/
+int pnpoly(int npol, double *xp, double *yp, double x, double y, int edgevalue) {
+	int i, j, c = 0;
+	double n1, n2, normp, scalar;
+
+	/*first test, are they colinear? if yes, is the point in the middle of the segment*/
+	if (edgevalue != 2 ){
+		for (i = 0, j = npol-1; i < npol; j = i++) {
+			n1=pow(yp[i]-yp[j],2.0)+pow(xp[i]-xp[j],2.0);
+			n2=pow(y-yp[j],2.0)+pow(x-xp[j],2.0);
+			normp=pow(n1*n2,0.5);
+			scalar=(yp[i]-yp[j])*(y-yp[j])+(xp[i]-xp[j])*(x-xp[j]);
+
+			if (scalar == normp){
+				if (n2<=n1){
+					c = edgevalue;
+					return c;
+				}
+			}
+		}
+	}
+	/*second test : point is neither on a vertex, nor on a side, where is it ?*/
+	for (i = 0, j = npol-1; i < npol; j = i++) {
+		if ((((yp[i]<=y) && (y<yp[j])) ||
+					((yp[j]<=y) && (y<yp[i]))) &&
+				(x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i])){
+			c = !c;
+		}
+	}
+	return c;
+}/*}}}*/
Index: /issm/trunk/src/c/shared/Exp/exp.h
===================================================================
--- /issm/trunk/src/c/shared/Exp/exp.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Exp/exp.h	(revision 15396)
@@ -7,16 +7,13 @@
 
 #include <cstring>
-#include "../../classes/objects/Contour.h"
-#include "../../shared/Numerics/recast.h"
-#include "../../Container/Container.h"
+#include "../Numerics/recast.h"
+#include "../Exceptions/exceptions.h"
+#include "../MemOps/MemOps.h"
 
 int IsInPolySerial(double* in,double* xc,double* yc,int numvertices,double* x,double* y,int nods, int edgevalue);
 int ExpWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,char* domainname);
-int ExpWrite(DataSet* contours,char* domainname);
 int pnpoly(int npol, double *xp, double *yp, double x, double y, int edgevalue);
 
-/*IsInPoly {{{*/
-template <class doubletype>
-int IsInPoly(SeqVec<doubletype>* in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue){
+template <class doubletype> int IsInPoly(doubletype* in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue){ /*{{{*/
 
 	int i;
@@ -40,5 +37,5 @@
 
 		//Get current value of value[i] -> do not change it if != 0
-		in->GetValue(&value,i);
+		value=in[i];
 		if (reCast<bool,doubletype>(value)){
 			/*this vertex already is inside one of the contours, continue*/
@@ -54,11 +51,9 @@
 			value=pnpoly(numvertices,xc,yc,x0,y0,edgevalue);
 		}
-		in->SetValue(i,value,INS_VAL);
+		in[i]=value;
 	}
 	 return 1;
 }/*}}}*/
-/*DomainOutlineRead{{{*/
-template <class doubletype>
-int DomainOutlineRead(int* pnprof,int** pprofnvertices,doubletype*** ppprofx,doubletype*** ppprofy,bool** pclosed,char* domainname){
+template <class doubletype> int ExpRead(int* pnprof,int** pprofnvertices,doubletype*** ppprofx,doubletype*** ppprofy,bool** pclosed,char* domainname){ /*{{{*/
 
 	/*indexing: */
@@ -91,12 +86,20 @@
 	nprof=1;
 	for(;;){
-		fscanf(fid,"%255s %255s\n",chardummy,chardummy);
-		fscanf(fid,"%255s %255s\n",chardummy,chardummy);
-		fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy);
-		fscanf(fid,"%20u %255s\n",&n,chardummy);
-		fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
-		for (i=0;i<n;i++) fscanf(fid,"%20lf %20lf\n",&ddummy,&ddummy);
+		//## Name:filename
+		if(fscanf(fid,"%255s %255s\n",chardummy,chardummy)!=2) _error_("Could not read " << domainname);
+		//## Icon:0
+		if(fscanf(fid,"%255s %255s\n",chardummy,chardummy)!=2) _error_("Could not read " << domainname);
+		//# Points Count Value
+		if(fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy)!=4) _error_("Could not read " << domainname);
+		if(fscanf(fid,"%20u %255s\n",&n,chardummy)!=2) _error_("Could not read number of points in "<<domainname);
+		//# X pos Y pos
+		if(fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy)!=5) _error_("Could not read " << domainname);
+		for (i=0;i<n;i++){
+			if(fscanf(fid,"%20lf %20lf\n",&ddummy,&ddummy)!=2){
+				_error_("Could not read coordinate of vertex "<< i <<" of "<<domainname);
+			}
+		}
 		/*check whether we are at the end of the file, otherwise, keep reading next profile:*/
-		if (feof(fid)) break;
+		if(feof(fid)) break;
 		nprof++;
 	}
@@ -119,13 +122,17 @@
 
 		/*Skip header: */
-		fscanf(fid,"%255s %255s\n",chardummy,chardummy);
-		fscanf(fid,"%255s %255s\n",chardummy,chardummy);
-		fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy);
+		//## Name:filename
+		if(fscanf(fid,"%255s %255s\n",chardummy,chardummy)!=2) _error_("Could not read " << domainname);
+		//## Icon:0
+		if(fscanf(fid,"%255s %255s\n",chardummy,chardummy)!=2) _error_("Could not read " << domainname);
+		//# Points Count Value
+		if(fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy)!=4) _error_("Could not read " << domainname);
 
 		/*Get number of profile vertices: */
-		fscanf(fid,"%20u %255s\n",&n,chardummy);
+		if(fscanf(fid,"%20u %255s\n",&n,chardummy)!=2) _error_("Could not read number of points in "<<domainname);
 
 		/*Skip next line: */
-		fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
+		//# X pos Y pos
+		if(fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy)!=5) _error_("Could not read " << domainname);
 
 		/*Allocate vertices: */
@@ -135,5 +142,7 @@
 		/*Read vertices: */
 		for (i=0;i<n;i++){
-			fscanf(fid,"%20lf %20lf\n",&x[i],&y[i]);
+			if(fscanf(fid,"%20lf %20lf\n",&x[i],&y[i])!=2){
+				_error_("Could not read coordinate of vertex "<<i<<" of "<<domainname);
+			}
 		}
 
@@ -161,33 +170,6 @@
 	if(pclosed) *pclosed=closed;
 	else         xDelete<bool>(closed);
-} /*}}}*/
-/*DataSet* DomainOutlineRead(char* domainname){{{*/
-template <class doubletype>
-DataSet* DomainOutlineRead(char* domainname){
+	return 1;
 
-	/*intermediary: */
-	int                  nprof;
-	int                 *profnvertices = NULL;
-	doubletype         **pprofx        = NULL;
-	doubletype         **pprofy        = NULL;
-
-	/*output: */
-	DataSet *domain = NULL;
-
-	/*If domainname is an empty string, return empty dataset*/
-	if (strcmp(domainname,"")==0){
-		nprof=0;
-	}
-	else{
-		DomainOutlineRead(&nprof,&profnvertices,&pprofx, &pprofy, NULL,domainname);
-	}
-
-	/*now create dataset of contours: */
-	domain=new DataSet(0);
-
-	for(int i=0;i<nprof;i++){
-		domain->AddObject(new Contour<doubletype>(i,profnvertices[i],pprofx[i],pprofy[i],1));
-	}
-	return domain;
 } /*}}}*/
 
Index: /issm/trunk/src/c/shared/LatLong/Ll2xyx.cpp
===================================================================
--- /issm/trunk/src/c/shared/LatLong/Ll2xyx.cpp	(revision 15396)
+++ /issm/trunk/src/c/shared/LatLong/Ll2xyx.cpp	(revision 15396)
@@ -0,0 +1,126 @@
+/*!\file Ll2xyx.cpp
+ */
+
+#include "../../shared/shared.h"
+#include "./latlong.h"
+#include <math.h>
+
+int Ll2xyx(double* x, double* y, double* lat, double* lon, int ncoord, int sgn){
+/*  This is a cpp conversion of the following:
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,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)
+*/
+	double  central_meridian,standard_parallel;
+
+	Ll2xydef(&central_meridian,&standard_parallel,sgn);
+
+	return(Ll2xyx(x,y,lat,lon,ncoord,sgn,central_meridian,standard_parallel));
+}
+
+int Ll2xyx(double* x, double* y, double* lat, double* lon, int ncoord, int sgn, double central_meridian, double standard_parallel){
+/*  This is a cpp conversion of the following:
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,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)
+*/
+
+	int     i,iret=0;
+	double  delta,slat;
+	double  cde,re,ex2,ex;
+	double  latitude,longitude;
+	double  T,rho,sl,tc,mc;
+
+	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
+
+	delta = central_meridian;
+	slat  = standard_parallel;
+
+	/*  Conversion constant from degrees to radians  */
+	cde = 57.29577951;
+	/*  Radius of the earth in meters  */
+	re  = 6378.273*pow(10.,3.);
+	/*  Eccentricity of the Hughes ellipsoid squared  */
+	ex2 = 0.006693883;
+	/*  Eccentricity of the Hughes ellipsoid  */
+	ex  =  sqrt(ex2);
+
+	/*  loop over all the coordinate pairs  */
+	for(i=0; i<ncoord; i++){
+		latitude  = fabs(lat[i]) * PI/180.;
+		longitude = (lon[i] + delta) * PI/180.;
+
+		/*  compute X and Y in grid coordinates.  */
+		T = tan(PI/4.-latitude/2.) / pow(((1.-ex*sin(latitude))/(1.+ex*sin(latitude))),(ex/2.));
+
+		if ((90. - slat) < 1.e-5)
+			rho = 2.*re*T/sqrt(pow((1.+ex),(1.+ex))*pow((1.-ex),(1.-ex)));
+		else {
+			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.)));
+			rho = re*mc*T/tc;
+		}
+
+		y[i]= -rho*(double)sgn*cos(sgn*longitude);
+		x[i]=  rho*(double)sgn*sin(sgn*longitude);
+
+		if (latitude>= PI/2.){
+			x[i] = 0.0;
+			y[i] = 0.0;
+			iret=1;
+		}
+	}
+	return(iret);
+}
+
+void Ll2xydef(double* pdelta, double* pslat, int sgn){
+/*  This is a cpp conversion of the following:
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,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)
+*/
+	bool    flag=true;
+
+	/*  Get central_meridian and standard_parallel depending on hemisphere  */
+	if (sgn ==  1) {
+		*pdelta= 45;
+		*pslat = 70;
+		if(flag) _printf0_("Info: creating coordinates in polar stereographic (Std Latitude: 70N Meridian: 45).\n");
+	}
+	else if (sgn == -1) {
+		*pdelta= 0;
+		*pslat = 71;
+		if(flag) _printf0_("Info: creating coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).\n");
+	}
+	else _error_("Sign should be either +1 or -1.\n");
+
+	return;
+}
Index: /issm/trunk/src/c/shared/LatLong/Xy2llx.cpp
===================================================================
--- /issm/trunk/src/c/shared/LatLong/Xy2llx.cpp	(revision 15396)
+++ /issm/trunk/src/c/shared/LatLong/Xy2llx.cpp	(revision 15396)
@@ -0,0 +1,134 @@
+/*!\file Xy2llx.cpp
+ */
+
+#include "../../shared/shared.h"
+#include "./latlong.h"
+#include <math.h>
+
+int Xy2llx(double* lat, double* lon, double* x, double* y, int ncoord, int sgn){
+/*  This is a cpp conversion of the following:
+%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)
+*/
+	double  central_meridian,standard_parallel;
+
+	Xy2lldef(&central_meridian,&standard_parallel,sgn);
+
+	return(Xy2llx(lat,lon,x,y,ncoord,sgn,central_meridian,standard_parallel));
+}
+
+int Xy2llx(double* lat, double* lon, double* x, double* y, int ncoord, int sgn, double central_meridian, double standard_parallel){
+/*  This is a cpp conversion of the following:
+%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)
+*/
+
+	int     i,iret=0;
+	double  delta,slat;
+	double  cde,re,ex2,ex;
+	double  sl,rho,cm,T,chi;
+
+	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
+
+	delta = central_meridian;
+	slat  = standard_parallel;
+
+	/*  Conversion constant from degrees to radians  */
+	cde  = 57.29577951;
+	/*  Radius of the earth in meters  */
+	re   = 6378.273*pow(10.,3.);
+	/*  Eccentricity of the Hughes ellipsoid squared  */
+	ex2  = 0.006693883;
+	/*  Eccentricity of the Hughes ellipsoid  */
+	ex   =  sqrt(ex2);
+
+	/*  loop over all the coordinate pairs  */
+	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.));
+		T  = tan((PI/4.0) - (sl/2.0))/pow(((1.0-ex*sin(sl))/(1.0+ex*sin(sl))),(ex/2.0));
+
+		if(fabs(slat-90.) < 1.e-5)
+			T =rho*sqrt(pow((1.+ex),(1.+ex))*pow((1.-ex),(1.-ex)))/2./re;
+		else
+			T =rho*T/(re*cm);
+
+		chi = (PI / 2.0) - 2.0 * atan(T);
+		lat[i] = chi + ((ex2 / 2.0) + (5.0 * pow(ex2,2.0) / 24.0) + (pow(ex2,3.0) / 12.0)) *
+			   sin(2.0 * chi) + ((7.0 * pow(ex2,2.0) / 48.0) + (29.0 * pow(ex2,3.0) / 240.0)) *
+			   sin(4.0 * chi) + (7.0 * pow(ex2,3.0) / 120.0) * sin(6.0 * chi) ;
+
+		lat[i] = (double)sgn * lat[i];
+		lon[i] = atan2((double)sgn * x[i],-(double)sgn * y[i]);
+		lon[i] = (double)sgn * lon[i];
+
+		if(rho <= 0.1){
+			lat[i] = 90. * (double)sgn;
+			lon[i] = 0.0;
+			iret=1;
+		}
+
+		lon[i] = lon[i] * 180. / PI;
+		lat[i] = lat[i] * 180. / PI;
+		lon[i] = lon[i] - delta; 
+	}
+
+	return(iret);
+}
+
+void Xy2lldef(double* pdelta, double* pslat, int sgn){
+/*  This is a cpp conversion of the following:
+%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)
+*/
+	bool    flag=true;
+
+	/*  Get central_meridian and standard_parallel depending on hemisphere  */
+	if (sgn == 1) {
+		*pdelta= 45;
+		*pslat = 70;
+		if(flag) _printf0_("Warning: expecting coordinates in polar stereographic (Std Latitude: 70N Meridian: 45).\n");
+	}
+	else if (sgn == -1) {
+		*pdelta= 0;
+		*pslat = 71;
+		if(flag) _printf0_("Warning: expecting coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).\n");
+	}
+	else _error_("Sign should be either +1 or -1.\n");
+
+	return;
+}
Index: /issm/trunk/src/c/shared/LatLong/latlong.h
===================================================================
--- /issm/trunk/src/c/shared/LatLong/latlong.h	(revision 15396)
+++ /issm/trunk/src/c/shared/LatLong/latlong.h	(revision 15396)
@@ -0,0 +1,16 @@
+/*!\file: latlong.h
+ * \brief prototypes for latlong.h
+ */ 
+
+#ifndef _SHARED_LATLONG_H_
+#define _SHARED_LATLONG_H_
+
+int Ll2xyx(double* x, double* y, double* lat, double* lon, int ncoord, int sgn);
+int Ll2xyx(double* x, double* y, double* lat, double* lon, int ncoord, int sgn, double central_meridian, double standard_parallel);
+void Ll2xydef(double* pdelta, double* pslat, int sgn);
+
+int Xy2llx(double* lat, double* lon, double* x, double* y, int ncoord, int sgn);
+int Xy2llx(double* lat, double* lon, double* x, double* y, int ncoord, int sgn, double central_meridian, double standard_parallel);
+void Xy2lldef(double* pdelta, double* pslat, int sgn);
+
+#endif //ifndef _SHARED_LATLONG_H_
Index: /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp
===================================================================
--- /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 15396)
@@ -5,13 +5,12 @@
 /*Headers*/
 /*{{{*/
-#include "./matrix.h"
-#include "../Exceptions/exceptions.h"
-#include "../Alloc/alloc.h"
 #include <stdio.h>
 #include <sys/types.h>
 #include <math.h>
 #include <float.h>    /*  DBL_EPSILON  */
-#include "../../include/include.h"
-#include "../../io/io.h"
+
+#include "./matrix.h"
+#include "../Exceptions/exceptions.h"
+#include "../MemOps/MemOps.h"
 /*}}}*/
 
@@ -206,6 +205,5 @@
 		pindx[ipiv]++;
 
-		//		_printf_(true,"pivot for i=%d: irow=%d, icol=%d, pindx[%d]=%d\n",
-		//				 i,irow,icol,ipiv,pindx[ipiv]);
+		//		_printf_("pivot for i=" << i << ": irow=" << irow << ", icol=" << icol  << ", pindx[" << ipiv << "]=" << pindx[ipiv] << "\n\n");
 
 		/*  switch rows to put pivot element on diagonal, noting that the
@@ -213,6 +211,5 @@
 
 		if (irow != icol) {
-			//			_printf_(true,"row switch for i=%d: irow=%d, icol=%d\n",
-			//					 i,irow,icol);
+			//			_printf_("row switch for i=" << i << ": irow=" << irow << ", icol=" << icol << "\n\n");
 
 			ipt=irow*ndim;
@@ -295,6 +292,5 @@
 			icol=pivrc2[j];
 
-			//			_printf_(true,"column switch back for j=%d: irow=%d, icol=%d\n",
-			//					 j,irow,icol);
+			//			_printf_("column switch back for j=" << j << ": irow=" << irow << ", icol=" << icol << "\n\n");
 
 			ipt=0;
Index: /issm/trunk/src/c/shared/Matrix/matrix.h
===================================================================
--- /issm/trunk/src/c/shared/Matrix/matrix.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Matrix/matrix.h	(revision 15396)
@@ -6,5 +6,5 @@
 #define _MATRIXUTILS_H_
 
-#include "../../include/include.h"
+#include "../Numerics/types.h"
 
 int  TripleMultiply( IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int nrowc, int ncolc, int itrnc, IssmDouble* d, int iaddd);
Index: /issm/trunk/src/c/shared/MemOps/MemOps.h
===================================================================
--- /issm/trunk/src/c/shared/MemOps/MemOps.h	(revision 15396)
+++ /issm/trunk/src/c/shared/MemOps/MemOps.h	(revision 15396)
@@ -0,0 +1,145 @@
+/* \file MemOps.h
+ * \brief: header file for memory allocations as well as templated new/delete checking for non-null pointers
+ */
+
+#ifndef _MEM_OPS_H_
+#define _MEM_OPS_H_
+
+#include <cassert>
+
+/* memory management of types T with non-trivial constructors require C++ style memory management*/
+#define USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+/* but for speed one may alternatively use C memory management but can do so safely only for T that are at most 
+ * plain old data structures (POD)*/
+#ifndef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+#include <cstdlib>
+#endif 
+
+template <class T> T* xNew(unsigned int size) { /*{{{*/
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+  T* aT_p=new T[size];
+  assert(aT_p);
+  return aT_p;
+#else
+  T* aT_p=(T*)malloc(size*sizeof(T));
+  assert(aT_p);
+  return aT_p;
+#endif  
+}/*}}}*/
+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** aT_pp =new T*[dim1];
+  assert(aT_pp );
+  for (unsigned int i=0;i<dim1;++i) {
+    aT_pp [i]=buf;
+    buf+=dim2;
+  }
+  return aT_pp ;
+#else
+  T* buf=(T*)malloc(dim1*dim2*sizeof(T));
+  assert(buf );
+  T** aT_pp =(T**)malloc(dim1*sizeof(T*));
+  assert(aT_pp );
+  for (unsigned int i=0;i<dim1;++i) {
+    aT_pp [i]=buf;
+    buf+=dim2;
+  }
+  return aT_pp ;
+#endif
+}/*}}}*/
+template <class T> T* xNewZeroInit(unsigned int size) {/*{{{*/
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+  T* aT_p=xNew<T>(size);
+  for (unsigned int i=0; i<size;++i) 
+    aT_p[i]=(T)0;
+  return aT_p;
+#else
+  T* aT_p=(T*)calloc(size,sizeof(T));
+  assert(aT_p);
+  return aT_p;
+#endif
+}/*}}}*/
+template <class T> T** xNewZeroInit(unsigned int dim1, unsigned int dim2) {/*{{{*/
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+  T** aT_pp=xNew<T>(dim1,dim2);
+  for (unsigned int i=0; i<dim1*dim2;++i)
+    (*aT_pp)[i]=(T)0;
+  return aT_pp;
+#else
+  T* buf=(T*)calloc(dim1*dim2*sizeof(T));
+  assert(buf );
+  T** aT_pp =(T**)malloc(dim1*sizeof(T*));
+  assert(aT_pp );
+  for (unsigned int i=0;i<dim1;++i) {
+    aT_pp [i]=buf;
+    buf+=dim2;
+  }
+  return aT_pp ;
+#endif
+}/*}}}*/
+template <class T> void xDelete(T**& aT_pp) {/*{{{*/
+  if (aT_pp) {
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+    delete [](*aT_pp);
+    delete [](aT_pp);
+#else
+    free((void*)*aT_pp)
+    free((void**)aT_pp);
+#endif
+  }
+  aT_pp=0;
+}/*}}}*/
+template <class T> void xDelete(T*& aT_p) {/*{{{*/
+  if (aT_p) 
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+    delete []aT_p;
+#else
+    free((void*)aT_p);
+#endif
+  aT_p=0;
+}/*}}}*/
+template <class T> T* xReNew(T* old, unsigned int old_size, unsigned int size) {/*{{{*/
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+	T* aT_p=0;
+	if (!old) { // no old memory
+		if (size)  
+		 aT_p=xNew<T>(size); // according to realloc behavior in manual page 
+	}
+	else { // have old memory
+		if (!size)  // but 0 size
+		 xDelete<T>(old); // according to realloc behavior in manual page
+		else { // non-zero size
+			assert(old_size); // have old memory - need to have old_size set or this call is bad
+			// allocate new, delete old; ; even for the case when size is 
+			// less than old_size we can't just keep the memory unchanged 
+			// because otherwise classes that have ctors/dtors with side-effects 
+			// may misbehave, for example classes with static instance/operations counters. 
+			aT_p=xNew<T>(size);
+			unsigned int iMax=(old_size<size)?old_size:size;
+			for (unsigned int i=0; i<iMax;++i) { 
+				// we need to copy the items by explicit assignments
+				aT_p[i]=old[i];
+			}
+			xDelete<T>(old);
+		}
+	}
+	return aT_p;
+#else
+	T* aT_p=0;
+	aT_p=(T*)realloc((void*)old,size*sizeof(T));
+	if (size) 
+	 assert(aT_p); // according to realloc behavior in manual page
+	return aT_p;
+#endif 
+}/*}}}*/
+template <class T>  T* xMemCpy(T* dest, const T* src, unsigned int size) {/*{{{*/
+  assert(dest); assert(src);
+  for (int i=0; i<size;++i) 
+    dest[i]=src[i];
+  return dest;
+};
+/*}}}*/
+
+#endif
Index: sm/trunk/src/c/shared/MemOps/xMemCpy.h
===================================================================
--- /issm/trunk/src/c/shared/MemOps/xMemCpy.h	(revision 15395)
+++ 	(revision )
@@ -1,18 +1,0 @@
-/* \file xMemCpy.h
- * \brief: header file for templated memory operations
- */
-
-#ifndef _XMEMCPY_H_
-#define _XMEMCPY_H_
-
-#include <cassert>
-
-template <class T> 
-T* xMemCpy(T* dest, const T* src, unsigned int size) {
-  assert(dest); assert(src);
-  for (int i=0; i<size;++i) 
-    dest[i]=src[i];
-  return dest;
-};
-
-#endif
Index: /issm/trunk/src/c/shared/Numerics/BrentSearch.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/BrentSearch.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/BrentSearch.cpp	(revision 15396)
@@ -9,11 +9,15 @@
 #endif
 
-#include "./numerics.h"
-#include "../../classes/objects/objects.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
-#include "../../shared/shared.h"
 #include <float.h>
 #include <iomanip>
+
+#include "../Exceptions/exceptions.h"
+#include "../io/io.h"
+#include "../MemOps/MemOps.h"
+#include "./Verbosity.h"
+#include "./OptPars.h"
+#include "./OptArgs.h"
+#include "./types.h"
+#include "./isnan.h"
 
 void BrentSearch(IssmDouble* psearch_scalar,IssmDouble* pJ,OptPars* optpars,IssmDouble (*f)(IssmDouble,OptArgs*), OptArgs* optargs){
@@ -46,11 +50,11 @@
 	if (xIsNan<IssmDouble>(fxmin)) _error_("Function evaluation returned NaN");
 	cout<<setprecision(5);
-	if(VerboseControl()) _pprintLine_("");
-	if(VerboseControl()) _pprintLine_("       Iteration         x           f(x)       Tolerance         Procedure");
-	if(VerboseControl()) _pprintLine_("");
-	if(VerboseControl()) _pprintLine_("           N/A    "<<setw(12)<<xmin<<"  "<<setw(12)<<fxmin<<"           N/A         boundary");
+	if(VerboseControl()) _printf0_("\n");
+	if(VerboseControl()) _printf0_("       Iteration         x           f(x)       Tolerance         Procedure\n");
+	if(VerboseControl()) _printf0_("\n");
+	if(VerboseControl()) _printf0_("           N/A    "<<setw(12)<<xmin<<"  "<<setw(12)<<fxmin<<"           N/A         boundary\n");
 	fxmax = (*f)(xmax,optargs);
 	if (xIsNan<IssmDouble>(fxmax)) _error_("Function evaluation returned NaN");
-	if(VerboseControl()) _pprintLine_("           N/A    "<<setw(12)<<xmax<<"  "<<setw(12)<<fxmax<<"           N/A         boundary");
+	if(VerboseControl()) _printf0_("           N/A    "<<setw(12)<<xmax<<"  "<<setw(12)<<fxmax<<"           N/A         boundary\n");
 
 	/*test if jump option activated and xmin==0*/
@@ -89,7 +93,7 @@
 	/*4: print result*/
 	if(VerboseControl())
-	 _pprintLine_("         "<<setw(5)<<iter<<"    "<<setw(12)<<xbest<<"  "<<setw(12)<<fxbest<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<"         initial");
+	 _printf0_("         "<<setw(5)<<iter<<"    "<<setw(12)<<xbest<<"  "<<setw(12)<<fxbest<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<"         initial\n");
 	if (!xIsNan<IssmDouble>(cm_jump) && (xmin==0) && ((fxbest/fxmin)<cm_jump)){
-		if(VerboseControl()) _pprintLine_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump);
+		if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump << "\n");
 		loop=false;
 	}
@@ -185,18 +189,18 @@
 		tol2=2.0*tol1;
 		if(VerboseControl())
-		 _pprintLine_("         "<<setw(5)<<iter<<"    "<<setw(12)<<x<<"  "<<setw(12)<<fx<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<
-					 "         "<<(goldenflag?"golden":"parabolic"));
+		 _printf0_("         "<<setw(5)<<iter<<"    "<<setw(12)<<x<<"  "<<setw(12)<<fx<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<
+					 "         "<<(goldenflag?"golden":"parabolic")<<"\n");
 
 		/*Stop the optimization?*/
 		if (sqrt(pow(xbest-xm,2)) < (tol2-0.5*(xmax-xmin))){
-			if(VerboseControl()) _pprintLine_("      optimization terminated: current x satisfies criteria 'tolx'=" << tolerance);
+			if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'tolx'=" << tolerance << "\n");
 			loop=false;
 		}
 		else if (iter>=maxiter){
-			if(VerboseControl()) _pprintLine_("      exiting: Maximum number of iterations has been exceeded  ('maxiter'=" << maxiter << ")");
+			if(VerboseControl()) _printf0_("      exiting: Maximum number of iterations has been exceeded  ('maxiter'=" << maxiter << ")\n");
 			loop=false;
 		}
 		else if (!xIsNan<IssmDouble>(cm_jump) && (xmin==0) && ((fxbest/fxmin)<cm_jump)){
-			if(VerboseControl()) _pprintLine_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump);
+			if(VerboseControl()) _printf0_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump << "\n");
 			loop=false;
 		}
Index: /issm/trunk/src/c/shared/Numerics/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Numerics/CMakeLists.txt	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/CMakeLists.txt	(revision 15396)
@@ -9,8 +9,6 @@
                $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/IsInputConverged.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/UnitConversion.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 15395)
+++ /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 15396)
@@ -1,10 +1,10 @@
 /*  Gauss point structures and prototypes  */
-
-#include "../../include/include.h"
-#include "./GaussPoints.h"
-#include "../Alloc/alloc.h"
-#include "../Exceptions/exceptions.h"
 #include <math.h>
 #include <float.h>
+
+#include "./GaussPoints.h"
+#include "../MemOps/MemOps.h"
+#include "../Exceptions/exceptions.h"
+#include "../Numerics/constants.h"
 
 /*General Gauss points*/
@@ -50,5 +50,5 @@
 		sizeof(wgt4 )/sizeof(IssmPDouble)};
 
-	//	_pprintLine_("Gauss-Legendre recurrence coefficients ngaus=" << ngaus);
+	//	_printf0_("Gauss-Legendre recurrence coefficients ngaus=" << ngaus << "\n");
 	*pxgaus =xNew<IssmPDouble>(ngaus);
 	*pxwgt  =xNew<IssmPDouble>(ngaus);
@@ -88,5 +88,5 @@
 }/*}}}*/
 /*FUNCTION GaussLegendreTria{{{*/
-void GaussLegendreTria( int* pngaus, IssmPDouble** pl1, IssmPDouble** pl2, IssmPDouble** pl3, IssmPDouble** pwgt, int iord ) {
+void GaussLegendreTria( int* pngaus, IssmDouble** pl1, IssmDouble** pl2, IssmDouble** pl3, IssmDouble** pwgt, int iord ) {
 	/*Gauss quadrature points for the triangle.
 
@@ -413,5 +413,5 @@
 		0.116251915907597, 0.025734050548330, 0.025734050548330};
 	/*}}}*/
-	/*  p=13, npoint=37  {{{*/
+	/*p=13, npoint=37  {{{*/
 	static IssmPDouble wgt13[]={
 		0.090968907790622, 0.019537784619314, 0.019537784619314, 
@@ -771,5 +771,5 @@
 		0.014663182224828};
 	/*}}}*/
-	/*  p=18, npoint=70  {{{*/
+	/*p=18, npoint=70  {{{*/
 
 	static IssmPDouble wgt18[]={
@@ -1138,5 +1138,5 @@
 		sizeof(wgt20)/sizeof(IssmPDouble)};
 
-	//	_pprintLine_("GaussLegendreTria: iord=" << iord);
+	//	_printf0_("GaussLegendreTria: iord=" << iord << "\n");
 
 	/*  check to see if Gauss points need to be calculated  */
@@ -1149,8 +1149,8 @@
 		*pngaus=np[iord-1];
 
-		*pl1  =xNew<IssmPDouble>(*pngaus);
-		*pl2  =xNew<IssmPDouble>(*pngaus);
-		*pl3  =xNew<IssmPDouble>(*pngaus);
-		*pwgt =xNew<IssmPDouble>(*pngaus);
+		*pl1  =xNew<IssmDouble>(*pngaus);
+		*pl2  =xNew<IssmDouble>(*pngaus);
+		*pl3  =xNew<IssmDouble>(*pngaus);
+		*pwgt =xNew<IssmDouble>(*pngaus);
 
 		for (i=0; i<*pngaus; i++) {
@@ -1167,8 +1167,8 @@
 		*pngaus=nigaus*nigaus;
 
-		*pl1  =xNew<IssmPDouble>(*pngaus);
-		*pl2  =xNew<IssmPDouble>(*pngaus);
-		*pl3  =xNew<IssmPDouble>(*pngaus);
-		*pwgt =xNew<IssmPDouble>(*pngaus);
+		*pl1  =xNew<IssmDouble>(*pngaus);
+		*pl2  =xNew<IssmDouble>(*pngaus);
+		*pl3  =xNew<IssmDouble>(*pngaus);
+		*pwgt =xNew<IssmDouble>(*pngaus);
 
 		/*  get the gauss points in each direction  */
@@ -1198,8 +1198,7 @@
 	}
 
-	//	_pprintLine_("GaussLegendreTria - ngaus=" << *pngaus);
+	//	_printf0_("GaussLegendreTria - ngaus=" << *pngaus << "\n");
 	//	for (i=0; i<*pngaus; i++)
-	//		_printf_(true,"i=%d: l1gaus=%f,l2gaus=%f,l3gaus=%f,wgt=%f\n",
-	//				 i,(*pl1 )[i],(*pl2 )[i],(*pl3 )[i],(*pwgt)[i]);
+	//		_printf0_("i=" << i << ": l1gaus=" << (*pl1 )[i] << ",l2gaus=" << (*pl2 )[i] << ",l3gaus=" << (*pl3 )[i]<< ",wgt=" << (*pwgt)[i]<< "\n\n");
 
 	return;
@@ -1397,5 +1396,5 @@
 		sizeof(wgt6 )/sizeof(IssmPDouble)};
 
-	//	_pprintLine_("GaussLegendreTetra: iord=" << iord);
+	//	_printf0_("GaussLegendreTetra: iord=" << iord << "\n");
 
 	/*  check to see if Gauss points need to be calculated  */
@@ -1520,5 +1519,5 @@
 		sizeof(wgt5 )/sizeof(IssmPDouble)};
 
-	//	_pprintLine_("Gauss-Lobatto recurrence coefficients ngaus=" << ngaus);
+	//	_printf0_("Gauss-Lobatto recurrence coefficients ngaus=" << ngaus << "\n");
 	*pxgaus =xNew<IssmPDouble>(ngaus);
 	*pxwgt  =xNew<IssmPDouble>(ngaus);
Index: /issm/trunk/src/c/shared/Numerics/GaussPoints.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/GaussPoints.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/GaussPoints.h	(revision 15396)
@@ -3,5 +3,5 @@
  */ 
 
-#include "../../include/types.h"
+#include "../../shared/Numerics/types.h"
 #ifndef _GAUSSPOINTS_H
 #define _GAUSSPOINTS_H
@@ -10,5 +10,5 @@
 void GaussLegendreLinear(IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus);
 #define MAX_TRIA_SYM_ORD    20
-void GaussLegendreTria(int* pngaus, IssmPDouble** pl1, IssmPDouble** pl2, IssmPDouble** pl3, IssmPDouble** pwgt, int iord);
+void GaussLegendreTria(int* pngaus, IssmDouble** pl1, IssmDouble** pl2, IssmDouble** pl3, IssmDouble** pwgt, int iord);
 #define MAX_TETRA_SYM_ORD    6
 void GaussLegendreTetra(int* pngaus, IssmPDouble** pl1, IssmPDouble** pl2, IssmPDouble** pl3, IssmPDouble** pl4, IssmPDouble** pwgt, int iord);
Index: sm/trunk/src/c/shared/Numerics/IsInputConverged.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/IsInputConverged.cpp	(revision 15395)
+++ 	(revision )
@@ -1,59 +1,0 @@
-/*!\file:  IsInputConverged.cpp
- * \brief: figure out convergence at the input level. 
- * We are given a list of inputs, new and old, and a criterion, and using the inputs, we 
- * return the value of the criterion test, which will be used at the solution level 
- * to determine convergence.
- */ 
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "../../classes/objects/objects.h"
-
-void IsInputConverged(IssmDouble* peps, Input** new_inputs,Input** old_inputs,int num_inputs,int criterion_enum){
-
-	int i,j;
-
-	/*output: */
-	IssmDouble eps;
-
-	/*intermediary: */
-	IssmDouble *newvalues     = NULL;
-	IssmDouble *oldvalues     = NULL;
-	int     num_values;
-	IssmDouble  ndu        = 0;
-	IssmDouble  nu         = 0;
-
-	if(criterion_enum==RelativeEnum){
-
-		/*conpute ndu/du (where u could be velocity, pressure, temperature, etc ...): */
-		for(i=0;i<num_inputs;i++){
-
-			/*in debugging mode, check that the inputs are of the same type*/
-			_assert_(new_inputs[i]->ObjectEnum()==old_inputs[i]->ObjectEnum());
-
-			/*Get pointers*/
-			new_inputs[i]->GetValuesPtr(&newvalues,&num_values);
-			old_inputs[i]->GetValuesPtr(&oldvalues,&num_values);
-			for(j=0;j<num_values;j++){
-				ndu+=pow(newvalues[j]-oldvalues[j],2);
-				nu+=pow(oldvalues[j],2);
-			}
-		}
-
-		/*take square root: */
-		ndu=sqrt(ndu);
-		nu=sqrt(nu);
-
-		/*now, compute eps: */
-		if(reCast<bool>(nu))eps=ndu/nu;
-		else eps=0;
-	}
-	else _error_("convergence criterion " << EnumToStringx(criterion_enum) << " not supported yet!");
-
-	/*Assign output pointers:*/
-	*peps=eps;
-}
Index: /issm/trunk/src/c/shared/Numerics/OptArgs.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/OptArgs.h	(revision 15396)
+++ /issm/trunk/src/c/shared/Numerics/OptArgs.h	(revision 15396)
@@ -0,0 +1,14 @@
+/*!\file:  OptArgs.h
+ * \brief place holder for optimization function arguments
+ */ 
+
+#ifndef _OPTARGS_H_
+#define _OPTARGS_H_
+
+class FemModel;
+
+struct OptArgs{
+	FemModel* femmodel;
+};
+
+#endif
Index: /issm/trunk/src/c/shared/Numerics/OptPars.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/OptPars.h	(revision 15396)
+++ /issm/trunk/src/c/shared/Numerics/OptPars.h	(revision 15396)
@@ -0,0 +1,19 @@
+/*!\file:  OptPars.h
+ * \brief place holder for optimization parameters
+ */ 
+
+#ifndef _OPTPARS_H_
+#define _OPTPARS_H_
+
+#include "./types.h"
+
+struct OptPars{
+
+	IssmDouble xmin;
+	IssmDouble xmax;
+	IssmDouble cm_jump;
+	int maxiter;
+
+};
+
+#endif
Index: /issm/trunk/src/c/shared/Numerics/OptimalSearch.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/OptimalSearch.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/OptimalSearch.cpp	(revision 15396)
@@ -9,10 +9,14 @@
 #endif
 
-#include "./numerics.h"
-#include "../../classes/objects/objects.h"
-#include "../../io/io.h"
-#include "../../include/include.h"
-#include "../../shared/shared.h"
 #include <float.h>
+
+#include "../Exceptions/exceptions.h"
+#include "../io/io.h"
+#include "../MemOps/MemOps.h"
+#include "./Verbosity.h"
+#include "./OptPars.h"
+#include "./OptArgs.h"
+#include "./types.h"
+#include "./isnan.h"
 
 void OptimalSearch(IssmDouble* psearch_scalar,IssmDouble* pJ,OptPars* optpars,IssmDouble (*f)(IssmDouble,OptArgs*), OptArgs* optargs){
@@ -43,8 +47,8 @@
 	if (xIsNan<IssmDouble>(fx1)) _error_("Function evaluation returned NaN");
 	cout<<setprecision(5);
-	if(VerboseControl()) _pprintLine_("");
-	if(VerboseControl()) _pprintLine_("       Iteration         x           f(x)       Tolerance");
-	if(VerboseControl()) _pprintLine_("");
-	if(VerboseControl()) _pprintLine_("           N/A    "<<setw(12)<<x1<<"  "<<setw(12)<<fx1<<"           N/A");
+	if(VerboseControl()) _printf0_("\n");
+	if(VerboseControl()) _printf0_("       Iteration         x           f(x)       Tolerance\n");
+	if(VerboseControl()) _printf0_("\n");
+	if(VerboseControl()) _printf0_("           N/A    "<<setw(12)<<x1<<"  "<<setw(12)<<fx1<<"           N/A\n");
 
 	//update tolerances
@@ -59,13 +63,13 @@
 		if (xIsNan<IssmDouble>(fx2)) _error_("Function evaluation returned NaN");
 		if(VerboseControl())
-		 _pprintLine_("         "<<setw(5)<<iter<<"    "<<setw(12)<<x2<<"  "<<setw(12)<<fx2<<"  "<<(fabs(x2-x1)>fabs(fx2-fx1)?fabs(fx2-fx1):fabs(x2-x1)));
+		 _printf0_("         "<<setw(5)<<iter<<"    "<<setw(12)<<x2<<"  "<<setw(12)<<fx2<<"  "<<(fabs(x2-x1)>fabs(fx2-fx1)?fabs(fx2-fx1):fabs(x2-x1)) << "\n");
 
 		//Stop the optimization?
 		if ((fabs(x2-x1)+seps)<tolerance || (fabs(fx2-fx1)+seps)<tolerance){
-			if(VerboseControl()) _pprintLine_("      " << "optimization terminated: the current x satisfies the termination criteria using 'tolx' of "  << tolerance);
+			if(VerboseControl()) _printf0_("      " << "optimization terminated: the current x satisfies the termination criteria using 'tolx' of "  << tolerance << "\n");
 			loop=false;
 		}
 		else if (iter>=maxiter){
-			if(VerboseControl()) _pprintLine_("      " << "exiting: Maximum number of iterations has been exceeded  - increase 'maxiter'");
+			if(VerboseControl()) _printf0_("      " << "exiting: Maximum number of iterations has been exceeded  - increase 'maxiter'\n");
 			loop=false;
 		}
Index: sm/trunk/src/c/shared/Numerics/OptionsFromAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/OptionsFromAnalysis.cpp	(revision 15395)
+++ 	(revision )
@@ -1,74 +1,0 @@
-/*!\file:  OptionsFromAnalysis.cpp
- * \brief: figure out ISSM options for current analysis, return a string.
- */ 
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include <cstring>
-
-#include "../../classes/objects/objects.h"
-#include "../../Container/Parameters.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-
-char* OptionsFromAnalysis(Parameters* parameters,int analysis_type){
-
-	/*output: */
-	char*   outstring=NULL;
-
-	/*intermediary: */
-	int     dummy;
-	IssmDouble* analyses=NULL;
-	char**  strings=NULL;
-	char*   string=NULL;
-	int     numanalyses;
-	int     found=-1;
-	int     i;
-
-	numanalyses=0;
-	parameters->FindParam(&strings,&numanalyses,PetscOptionsStringsEnum);
-
-	parameters->FindParam(&analyses,&dummy,PetscOptionsAnalysesEnum);
-
-	if(numanalyses==0)return NULL; //we did not find petsc options, don't bother.
-
-	/*ok, go through analyses and figure out if it corresponds to our analysis_type: */
-	found=-1;
-	for(i=0;i<numanalyses;i++){
-		if (analyses[i]==analysis_type){
-			/*found the analysis, get out of here: */
-			found=i;
-			break;
-		}
-	}
-	if(found==-1){
-		/*still haven't found a list of petsc options, go find the default one, for analysis type NoneAnalysisEnum: */
-		for(i=0;i<numanalyses;i++){
-			if (analyses[i]==NoneAnalysisEnum){
-				/*found the default analysis, get out of here: */
-				found=i;
-				break;
-			}
-		}
-	}
-	if (found==-1){
-		/*ok, we did not find anything, this is not good! error out: */
-		_error_("could find neither a default analysis  nor analysis " << EnumToStringx(analysis_type));
-	}
-
-	/*ok, grab the option string: */
-	outstring=xNew<char>(strlen(strings[found])+1);
-	strcpy(outstring,strings[found]);
-
-	/*Free ressources*/
-	xDelete<IssmDouble>(analyses);
-	for(i=0;i<numanalyses;i++){
-		string=strings[i];
-		xDelete<char>(string);
-	}
-	xDelete<char*>(strings);
-	return outstring;
-}
Index: sm/trunk/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp	(revision 15395)
+++ 	(revision )
@@ -1,42 +1,0 @@
-/*!\file:  PetscOptionsFromAnalysis.cpp
- * \brief: change petsc options using analysis type and parameters
- */ 
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "../../classes/objects/objects.h"
-#include "../../Container/Parameters.h"
-#include "../../toolkits/toolkits.h"
-
-void PetscOptionsFromAnalysis(Parameters* parameters,int analysis_type){
-
-	/*intermediary: */
-	char* options=NULL;
-
-	/*Recover first the options string for this analysis: */
-	options=OptionsFromAnalysis(parameters,analysis_type);
-
-	/*now, reset the options database with this string. Taken from petsc/install/src/sys/objects/pinit.c. This 
-	 *capability is not covered by Petsc!: */
-
-	#if _PETSC_MAJOR_ == 2 
-	PetscOptionsDestroy();
-	PetscOptionsCreate();
-	//PetscOptionsCheckInitial_Private();
-	//PetscOptionsCheckInitial_Components();
-	PetscOptionsSetFromOptions();
-	PetscOptionsInsertMultipleString(options); //our patch
-	#else
-	PetscOptionsSetFromOptions();
-	PetscOptionsClear();
-	//PetscOptionsSetFromOptions();
-	PetscOptionsInsertMultipleString(options); //our patch
-	#endif
-
-	/*Free ressources:*/
-	xDelete<char>(options);
-}
Index: /issm/trunk/src/c/shared/Numerics/Synchronize.sh
===================================================================
--- /issm/trunk/src/c/shared/Numerics/Synchronize.sh	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/Synchronize.sh	(revision 15396)
@@ -27,5 +27,4 @@
 #endif
 #include "./Verbosity.h"
-#include "../../include/macros.h"
 #include "../Exceptions/exceptions.h"
 /*}}}*/
Index: sm/trunk/src/c/shared/Numerics/UnitConversion.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/UnitConversion.cpp	(revision 15395)
+++ 	(revision )
@@ -1,76 +1,0 @@
-/*!\file:  UnitConversion.cpp
- * \brief: convert units from the model to IU or from IU to the model.
- */ 
-
-/*headers {{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "../../Container/Container.h"
-#include "../../classes/objects/objects.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../shared/shared.h"
-
-IssmDouble UnitConversionScaleFactor(int type_enum);
-/*}}}*/
-
-void UnitConversion(IssmDouble* values, int numvalues,int direction_enum, int type_enum){
-
-	IssmDouble scale;
-	int i;
-
-	/*Get scaling factor: */
-	scale=UnitConversionScaleFactor(type_enum);
-
-	/*Now, which direction are we going? once determined, use scale factor: */
-	if(direction_enum==IuToExtEnum) for(i=0;i<numvalues;i++)values[i]=values[i]*scale; 
-	else if(direction_enum==ExtToIuEnum) for(i=0;i<numvalues;i++)values[i]=values[i]/scale; 
-	else _error_("wrong direction for unit conversion, either IuToExtEnum or ExtToIuEnum. ");
-
-}
-
-IssmDouble UnitConversion(IssmDouble value, int direction_enum, int type_enum){
-
-	UnitConversion(&value,1,direction_enum,type_enum);
-
-	return value;
-}
-
-IssmDouble UnitConversionScaleFactor(int type_enum){
-
-	IssmDouble yts=365.0*24.0*3600.0;
-
-	IssmDouble scale;
-	switch(type_enum){
-		case TimesteppingStartTimeEnum:              scale=1.0/yts;break; //yr
-		case TimesteppingFinalTimeEnum:              scale=1.0/yts;break; //yr
-		case TimesteppingTimeStepEnum:               scale=1.0/yts;break; //yr
-		case TimeEnum:                               scale=1.0/yts;break; //yr
-		case HydrologyWaterVxEnum:                   scale=yts;break;     //m/yr
-		case HydrologyWaterVyEnum:                   scale=yts;break;     //m/yr
-		case VxEnum:                                 scale=yts;break;     //m/yr
-		case InversionVxObsEnum:                     scale=yts;break;     //m/yr
-		case VyEnum:                                 scale=yts;break;     //m/yr
-		case InversionVyObsEnum:                     scale=yts;break;     //m/yr
-		case VzEnum:                                 scale=yts;break;     //m/yr
-		case InversionVzObsEnum:                     scale=yts;break;     //m/yr
-		case VelEnum:                                scale=yts;break;     //m/yr
-		case InversionVelObsEnum:                    scale=yts;break;     //m/yr
-		case BalancethicknessThickeningRateEnum:     scale=yts;break;     //m/yr
-		case BasalforcingsMeltingRateEnum:           scale=yts;break;     //m/yr
-		case BasalforcingsMeltingRateCorrectionEnum: scale=yts;break;     //m/yr
-		case SurfaceforcingsPrecipitationEnum:       scale=yts;break;     //m/yr
-		case SurfaceforcingsMassBalanceEnum:         scale=yts;break;     //m/yr
-		case SurfaceforcingsBPosEnum:						scale=yts;break;     //m/yr
-		case SurfaceforcingsBNegEnum:						scale=yts;break;     //m/yr
-		case SurfaceforcingsSmbrefEnum:					scale=yts;break;     //m/yr
-		case MisfitEnum:                             scale=pow(yts,2);break; //(m/yr)^2
-		case MassFluxEnum:                           scale=pow((IssmDouble)10,-12)*yts;break; // (GigaTon/year)
-		case TotalSmbEnum:                           scale=pow((IssmDouble)10,-12)*yts;break; // (GigaTon/year)
-		default: scale=1.0; break;
-	}
-	return scale;
-}
Index: /issm/trunk/src/c/shared/Numerics/Verbosity.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/Verbosity.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/Verbosity.cpp	(revision 15396)
@@ -16,5 +16,4 @@
 #endif
 #include "./Verbosity.h"
-#include "../../include/macros.h"
 #include "../Exceptions/exceptions.h"
 /*}}}*/
Index: /issm/trunk/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp	(revision 15396)
@@ -1,7 +1,8 @@
-#include "../Alloc/alloc.h"
-#include "../../include/include.h"
+#include <math.h>
+
+#include "../MemOps/MemOps.h"
 #include "../Exceptions/exceptions.h"
+#include "../Numerics/types.h"
 #include "./isnan.h"
-#include <math.h>
 
 void XZvectorsToCoordinateSystem(IssmDouble* T,IssmDouble* xzvectors){
Index: /issm/trunk/src/c/shared/Numerics/constants.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/constants.h	(revision 15396)
+++ /issm/trunk/src/c/shared/Numerics/constants.h	(revision 15396)
@@ -0,0 +1,41 @@
+/*!\file: constants.h
+ * \brief prototypes for constants.h
+ */ 
+
+#ifndef _ISSM_CONSTANTS_H_
+#define _ISSM_CONSTANTS_H_
+
+#define UNDEF -9999
+#define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
+#define SQRT2 1.414213562373095048801688724209698078569671875376948073176679738
+#define SQRT3 1.732050807568877293527446341505872366942805253810380628055806979
+#define PI 3.141592653589793238462643383279502884197169399375105820974944592308
+
+#define NDOF1 1
+#define NDOF2 2
+#define NDOF3 3
+#define NDOF4 4
+
+#define DIM2 2
+#define DIM3 3
+
+/*Windows specific typefefs: */
+#ifdef _INTEL_WIN_
+
+/*Complicated way, which does not handle INFINITY though: */
+/*#ifndef NAN
+	static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff};
+	#define NAN (*(const float *) __nan)
+#endif*/
+
+//For reference, for Intel compile on win64
+//#define NAN 0.0/0.0 
+//#define INFINITY 1.0/0.0
+
+//Most generic way it would seem:
+#define INFINITY (DBL_MAX+DBL_MAX)
+#define NAN (INFINITY-INFINITY)
+
+#endif
+
+#endif //ifndef _ISSMTYPEDEFS_H_
Index: /issm/trunk/src/c/shared/Numerics/cross.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/cross.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/cross.cpp	(revision 15396)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../include/include.h"
+#include "./types.h"
 
 void cross(IssmDouble* result,IssmDouble* vector1,IssmDouble* vector2){
Index: /issm/trunk/src/c/shared/Numerics/cubic.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/cubic.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/cubic.cpp	(revision 15396)
@@ -1,3 +1,4 @@
 #include <math.h>
+
 #include "./numerics.h"
 
Index: /issm/trunk/src/c/shared/Numerics/extrema.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/extrema.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/extrema.cpp	(revision 15396)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../include/include.h"
+#include "./types.h"
 
 IssmDouble min(IssmDouble a,IssmDouble b){
@@ -27,2 +27,13 @@
 	else return b;
 }
+
+#ifdef _HAVE_ADOLC_
+IssmPDouble  min(IssmPDouble a,IssmPDouble b){
+	if (a<b)return a;
+	else return b;
+}
+IssmPDouble  max(IssmPDouble a,IssmPDouble b){
+	if (a>b)return a;
+	else return b;
+}
+#endif
Index: /issm/trunk/src/c/shared/Numerics/isnan.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/isnan.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/isnan.cpp	(revision 15396)
@@ -7,5 +7,4 @@
 #endif
 
-#include "../../include/include.h"
 #include "isnan.h"
 
Index: /issm/trunk/src/c/shared/Numerics/isnan.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/isnan.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/isnan.h	(revision 15396)
@@ -24,4 +24,5 @@
 
 #if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+#include "./types.h"
 template <> int xIsNan<adouble> (const adouble& X);
 #endif
Index: /issm/trunk/src/c/shared/Numerics/numerics.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/numerics.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/numerics.h	(revision 15396)
@@ -6,17 +6,27 @@
 #define  _NUMERICS_H_
 
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
 #include "./Verbosity.h"
 #include "./GaussPoints.h"
 #include "./isnan.h"
 #include "./recast.h"
-
-class Input;
-class Parameters;
-
-struct OptArgs;
-struct OptPars;
+#include "./types.h"
+#include "./constants.h"
+#include "./OptArgs.h"
+#include "./OptPars.h"
 
 IssmDouble  min(IssmDouble a,IssmDouble b);
 IssmDouble  max(IssmDouble a,IssmDouble b);
+
+#ifdef _HAVE_ADOLC_
+IssmPDouble  min(IssmPDouble a,IssmPDouble b);
+IssmPDouble  max(IssmPDouble a,IssmPDouble b);
+#endif
+
 int         min(int a,int b);
 int         max(int a,int b);
@@ -25,13 +35,6 @@
 void        OptimalSearch(IssmDouble *psearch_scalar,IssmDouble*pJ,OptPars*optpars,IssmDouble (*f)(IssmDouble,OptArgs*), OptArgs*optargs);
 void        cross(IssmDouble *result,IssmDouble*vector1,IssmDouble*vector2);
-void        IsInputConverged(IssmDouble *peps, Input**new_inputs,Input**old_inputs,int num_inputs,int criterion_enum);
-void        UnitConversion(IssmDouble *values, int numvalues,int direction_enum, int type_enum);
-IssmDouble  UnitConversion(IssmDouble value, int direction_enum, int type_enum);
-char       *OptionsFromAnalysis(Parameters *parameters,int analysis_type);
 void        XZvectorsToCoordinateSystem(IssmDouble *T,IssmDouble*xzvectors);
 int         cubic(IssmDouble a, IssmDouble b, IssmDouble c, IssmDouble d, double X[3], int *num);
-#ifdef _HAVE_PETSC_
-void   PetscOptionsFromAnalysis(Parameters* parameters,int analysis_type);
-#endif
 
 #endif //ifndef _NUMERICS_H_
Index: /issm/trunk/src/c/shared/Numerics/recast.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/recast.h	(revision 15395)
+++ /issm/trunk/src/c/shared/Numerics/recast.h	(revision 15396)
@@ -17,18 +17,16 @@
 #if !defined(_HAVE_ADOLC_) || defined(_WRAPPERS_)
 
-template<class To, class From>
-To reCast(const From& from) {
+template<class To, class From> To reCast(const From& from) {
     return (To)from;
 }
 
 #else
+#include "./types.h"
 
-template<class To, class From>
-struct ForPartialSpecialization {
+template<class To, class From> struct ForPartialSpecialization {
     static  To reCast(const From& from ) { return (To) from;}
 };
 
-template<class To, class From>
-To reCast(const From& from) {
+template<class To, class From> To reCast(const From& from) {
     return ForPartialSpecialization<To,From>::reCast(from);
 }
@@ -36,6 +34,5 @@
  * partial specialization
  */
-template<class To>
-struct ForPartialSpecialization<To,adouble> {
+template<class To> struct ForPartialSpecialization<To,adouble> {
     static  To reCast(const adouble& from ) { return (To) (from.getValue());}
 };
Index: /issm/trunk/src/c/shared/Numerics/types.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/types.h	(revision 15396)
+++ /issm/trunk/src/c/shared/Numerics/types.h	(revision 15396)
@@ -0,0 +1,38 @@
+/*!\file: types.h
+ * \brief prototypes for types.h
+ */ 
+
+#ifndef _TYPES_H_
+#define  _TYPES_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+
+/*here are our abstracted types: inspired on petsc */
+#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  
+
+#if defined(_HAVE_ADOLC_) &&  !defined(_WRAPPERS_)
+#include "adolc/adolc.h"
+// for active variables
+typedef adouble IssmDouble;
+// for passive variables
+typedef double IssmPDouble;
+#else 
+// see above
+typedef double IssmDouble; 
+// see above
+typedef IssmDouble IssmPDouble;
+#endif
+
+#endif //ifndef _TYPES_H_
Index: /issm/trunk/src/c/shared/Sorting/binary_search.cpp
===================================================================
--- /issm/trunk/src/c/shared/Sorting/binary_search.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Sorting/binary_search.cpp	(revision 15396)
@@ -9,4 +9,5 @@
 #endif
 
+#include "../Exceptions/exceptions.h"
 #include <stdio.h>
 
@@ -21,4 +22,6 @@
 	int *end = NULL;
 	int *mid = NULL;
+
+	_assert_(sorted_integers);
 
 	// point to beginning and end of the array
Index: /issm/trunk/src/c/shared/String/ApiPrintf.cpp
===================================================================
--- /issm/trunk/src/c/shared/String/ApiPrintf.cpp	(revision 15396)
+++ /issm/trunk/src/c/shared/String/ApiPrintf.cpp	(revision 15396)
@@ -0,0 +1,15 @@
+/*!\file:  ApiPrintf: this file only gets compiled and linked for issm.exe. API specific 
+ * versions of this file (for Python and Matlab) will be used for the wrappers (modules). 
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+
+void ApiPrintf(const char* string){
+	printf("%s",string);
+}
Index: /issm/trunk/src/c/shared/String/DescriptorIndex.cpp
===================================================================
--- /issm/trunk/src/c/shared/String/DescriptorIndex.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/String/DescriptorIndex.cpp	(revision 15396)
@@ -14,6 +14,7 @@
 #include <string.h>
 #include <ctype.h>
-#include "../shared.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../Enum/Enum.h"
+#include "../io/io.h"
+#include "../Exceptions/exceptions.h"
 
 int  DescriptorIndex(char* root, int* pindex,char* descriptor){ //We assume root has already been allocated, and we just have to copy into it.
Index: /issm/trunk/src/c/shared/String/sharedstring.h
===================================================================
--- /issm/trunk/src/c/shared/String/sharedstring.h	(revision 15395)
+++ /issm/trunk/src/c/shared/String/sharedstring.h	(revision 15396)
@@ -12,3 +12,5 @@
 #endif
 
+void ApiPrintf(const char* string);
+
 #endif //ifndef _SHAREDSTRING_H_
Index: sm/trunk/src/c/shared/String/stricmp.c
===================================================================
--- /issm/trunk/src/c/shared/String/stricmp.c	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-/* \file stricmp.cpp
- * \brief bypass non-standard stricmp
- */
-
-#ifndef WIN32
-
-#include <strings.h>
-int stricmp(const char* a,const char* b){
-	return  strcasecmp(a,b);
-}
-#endif
Index: /issm/trunk/src/c/shared/String/stricmp.cpp
===================================================================
--- /issm/trunk/src/c/shared/String/stricmp.cpp	(revision 15396)
+++ /issm/trunk/src/c/shared/String/stricmp.cpp	(revision 15396)
@@ -0,0 +1,11 @@
+/* \file stricmp.cpp
+ * \brief bypass non-standard stricmp
+ */
+
+#ifndef WIN32
+
+#include <strings.h>
+int stricmp(const char* a,const char* b){
+	return  strcasecmp(a,b);
+}
+#endif
Index: /issm/trunk/src/c/shared/Threads/LaunchThread.cpp
===================================================================
--- /issm/trunk/src/c/shared/Threads/LaunchThread.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/Threads/LaunchThread.cpp	(revision 15396)
@@ -20,7 +20,6 @@
 
 #include "./issm_threads.h"
-#include "../Alloc/xNewDelete.h"
+#include "../MemOps/MemOps.h"
 #include "../Exceptions/exceptions.h"
-#include "../../include/include.h"
 
 void LaunchThread(void* function(void*), void* gate,int num_threads){
Index: /issm/trunk/src/c/shared/TriMesh/SplitMeshForRifts.cpp
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 15396)
@@ -3,6 +3,5 @@
  */
 #include "./trimesh.h"
-#include "../Alloc/xNewDelete.h"
-#include "../Alloc/alloc.h"
+#include "../MemOps/MemOps.h"
 
 int SplitMeshForRifts(int* pnel,int** pindex,int* pnods,double** px,double** py,int* pnsegs,int** psegments,int** psegmentmarkerlist){
Index: /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 15395)
+++ /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 15396)
@@ -7,7 +7,5 @@
 #include "./trimesh.h"
 #include "../Exceptions/exceptions.h"
-#include "../Alloc/xNewDelete.h"
-#include "../Alloc/alloc.h"
-#include "../../include/include.h"
+#include "../MemOps/MemOps.h"
 
 #define RIFTPENALTYPAIRSWIDTH 8
Index: /issm/trunk/src/c/shared/io/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/io/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/shared/io/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,9 @@
+# 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: /issm/trunk/src/c/shared/io/Comm/Comm.h
===================================================================
--- /issm/trunk/src/c/shared/io/Comm/Comm.h	(revision 15396)
+++ /issm/trunk/src/c/shared/io/Comm/Comm.h	(revision 15396)
@@ -0,0 +1,11 @@
+/*\file Comm.h
+ *\brief: communicator information
+ */
+
+#ifndef _IO_COMM_H_
+#define _IO_COMM_H_
+
+#include "./CommDef.h"
+#include "./IssmComm.h"
+
+#endif
Index: /issm/trunk/src/c/shared/io/Comm/CommDef.h
===================================================================
--- /issm/trunk/src/c/shared/io/Comm/CommDef.h	(revision 15396)
+++ /issm/trunk/src/c/shared/io/Comm/CommDef.h	(revision 15396)
@@ -0,0 +1,16 @@
+/*\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 15396)
+++ /issm/trunk/src/c/shared/io/Comm/IssmComm.cpp	(revision 15396)
@@ -0,0 +1,61 @@
+/*! \file IssmComm.cpp
+ * \brief  file containing the methods for IssmComm.h
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./IssmComm.h"
+#include "../../Numerics/types.h"
+#include "../../Exceptions/exceptions.h"
+
+void IssmComm::SetComm(COMM incomm){ /*{{{*/
+
+	/*A comm is provided, we are running in parallel (this is not a module)*/
+	parallel = true;
+	comm     = incomm;
+
+}/*}}}*/
+void IssmComm::SetComm(void){ /*{{{*/
+
+	/*no comm provided, This is a matlab/python module*/
+	parallel = false;
+
+	/*No need to initialise comm*/
+
+}/*}}}*/
+COMM IssmComm::GetComm(){  /*{{{*/
+	if(!parallel) _error_("Cannot return comm in serial mode");
+	return comm;
+}/*}}}*/
+int IssmComm::GetRank(){  /*{{{*/
+
+	int my_rank = 0;
+
+	/*for matlab and python modules*/
+	if(!parallel) return my_rank;
+
+	#ifdef _HAVE_MPI_
+	MPI_Comm_rank(comm,&my_rank);
+	#endif
+
+	return my_rank;
+
+}/*}}}*/
+int IssmComm::GetSize(){  /*{{{*/
+
+	int size = 1;
+
+	/*for matlab and python modules*/
+	if(!parallel) return size;
+
+	#ifdef _HAVE_MPI_
+	MPI_Comm_size(comm,&size);
+	#endif
+
+	return size;
+
+}/*}}}*/
Index: /issm/trunk/src/c/shared/io/Comm/IssmComm.h
===================================================================
--- /issm/trunk/src/c/shared/io/Comm/IssmComm.h	(revision 15396)
+++ /issm/trunk/src/c/shared/io/Comm/IssmComm.h	(revision 15396)
@@ -0,0 +1,34 @@
+/* \file IssmComm.h
+ * \brief  create a class with a static comm, and static methods to access it
+ * This is a way of protecting access to the communicator.
+ */
+
+#ifndef _ISSM_COMM_H
+#define _ISSM_COMM_H
+
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./CommDef.h"
+
+/*}}}*/
+
+class IssmComm {
+
+	private:
+		static COMM comm;
+		static bool parallel;
+
+	public:
+		static void SetComm(COMM incomm);
+		static void SetComm(void);
+		static COMM GetComm(void);
+		static int GetRank(void);
+		static int GetSize(void);
+};
+
+#endif  /* _ISSM_COMM_H */
Index: /issm/trunk/src/c/shared/io/Disk/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/io/Disk/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/shared/io/Disk/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,10 @@
+# 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 15396)
+++ /issm/trunk/src/c/shared/io/Disk/WriteLockFile.cpp	(revision 15396)
@@ -0,0 +1,25 @@
+/*!\file:  WriteLockFile.cpp
+ * \brief
+ */ 
+#include "../../Exceptions/exceptions.h"
+#include "../Comm/Comm.h"
+#include "../Print/Print.h"
+
+void WriteLockFile(char* filename){
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+
+	/* output: */
+	FILE* fid=NULL;
+
+	/* Open lock file and write 1 into it: */
+	if(my_rank==0){
+		fid=fopen(filename,"w");
+		if(fid==NULL) _error_("error message: could not open lock file " << filename);
+
+		/*Close file: */
+		if(fclose(fid)!=0) _error_("could not close lock file " << filename);
+	}
+
+}	
Index: /issm/trunk/src/c/shared/io/Disk/diskio.h
===================================================================
--- /issm/trunk/src/c/shared/io/Disk/diskio.h	(revision 15396)
+++ /issm/trunk/src/c/shared/io/Disk/diskio.h	(revision 15396)
@@ -0,0 +1,14 @@
+/*\file diskio.h
+ *\brief: I/O for ISSM from disk
+ */
+
+#ifndef _DISK_IO_H_
+#define _DISK_IO_H_
+
+#include <stdio.h>
+
+FILE* pfopen(char* filename,const char* format);
+void  pfclose(FILE* fid,char* filename);
+void WriteLockFile(char* filename);
+
+#endif	/* _IO_H_ */
Index: /issm/trunk/src/c/shared/io/Disk/pfclose.cpp
===================================================================
--- /issm/trunk/src/c/shared/io/Disk/pfclose.cpp	(revision 15396)
+++ /issm/trunk/src/c/shared/io/Disk/pfclose.cpp	(revision 15396)
@@ -0,0 +1,19 @@
+/*!\file:  pfclose.cpp
+ * \brief fclose wrapper for parallel solution
+ */ 
+
+#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.h"
+
+void pfclose(FILE* fid,char* filename){
+
+	/*Close file handle: */
+	_assert_(fid);
+	if(fclose(fid)!=0)_error_("could not close file " << filename);
+}
Index: /issm/trunk/src/c/shared/io/Disk/pfopen.cpp
===================================================================
--- /issm/trunk/src/c/shared/io/Disk/pfopen.cpp	(revision 15396)
+++ /issm/trunk/src/c/shared/io/Disk/pfopen.cpp	(revision 15396)
@@ -0,0 +1,23 @@
+/*!\file:  pfopen.cpp
+ * \brief fopen wrapper for parallel solution
+ */ 
+
+#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.h"
+
+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"); 
+
+	return fid;
+}
Index: /issm/trunk/src/c/shared/io/Print/Print.h
===================================================================
--- /issm/trunk/src/c/shared/io/Print/Print.h	(revision 15396)
+++ /issm/trunk/src/c/shared/io/Print/Print.h	(revision 15396)
@@ -0,0 +1,40 @@
+/*\file Print.h
+ *\brief: print I/O for ISSM
+ */
+
+#ifndef _ISSM_PRINT_H_
+#define _ISSM_PRINT_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif 
+
+#include <string>
+#include <iostream>
+#include <sstream>
+#include <iomanip>
+
+using namespace std;
+/*macros:*/
+/* _printf_{{{*/
+/* macro to print some string on all cpus */
+#define _printf_(StreamArgs)\
+  do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+	  aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs; \
+	  PrintfFunctionOnAllCpus(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+/*}}}*/
+/* _printf0_ {{{*/
+/* macro to print some string only on cpu 0 */
+#define _printf0_(StreamArgs)\
+  do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+	  aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs; \
+	  PrintfFunctionOnCpu0(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+/*}}}*/
+
+/*functions: */
+int PrintfFunctionOnCpu0(const string & message);
+int PrintfFunctionOnAllCpus(const string & message);
+
+#endif	
Index: /issm/trunk/src/c/shared/io/Print/PrintfFunction.cpp
===================================================================
--- /issm/trunk/src/c/shared/io/Print/PrintfFunction.cpp	(revision 15396)
+++ /issm/trunk/src/c/shared/io/Print/PrintfFunction.cpp	(revision 15396)
@@ -0,0 +1,46 @@
+/*\file PrintfFunction.c
+ *\brief: this function is used by the _printf_ macro, to take into account the 
+ *fact we may be running on a cluster. 
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdarg.h>
+#include <cstdio>
+#ifdef _HAVE_ANDROID_NDK_
+#include <android/log.h>
+#endif
+#include "./Print.h"
+#include "../Comm/Comm.h"
+#include "../../String/sharedstring.h"
+#include "../../MemOps/MemOps.h"
+
+int PrintfFunctionOnCpu0(const string & message){
+	int  my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(my_rank==0){
+		#ifdef _HAVE_ANDROID_JNI_
+		__android_log_print(ANDROID_LOG_INFO, "Native",message.c_str());
+		#else
+		ApiPrintf(message.c_str());
+		#endif
+	}
+	return 1;
+}
+int PrintfFunctionOnAllCpus(const string & message){
+
+	#ifdef _HAVE_ANDROID_JNI_
+	__android_log_print(ANDROID_LOG_INFO, "Native",message.c_str());
+	#else
+	ApiPrintf(message.c_str());
+	#endif
+
+	return 1;
+}
Index: /issm/trunk/src/c/shared/io/io.h
===================================================================
--- /issm/trunk/src/c/shared/io/io.h	(revision 15396)
+++ /issm/trunk/src/c/shared/io/io.h	(revision 15396)
@@ -0,0 +1,18 @@
+/*\file io.h
+ *\brief: I/O for ISSM
+ */
+
+#ifndef _ISSM_IO_H_
+#define _ISSM_IO_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif 
+
+#include "./Disk/diskio.h"
+#include "./Print/Print.h"
+#include "./Comm/Comm.h"
+
+#endif	/* _IO_H_ */
Index: /issm/trunk/src/c/shared/shared.h
===================================================================
--- /issm/trunk/src/c/shared/shared.h	(revision 15395)
+++ /issm/trunk/src/c/shared/shared.h	(revision 15396)
@@ -6,12 +6,12 @@
 #define _SHARED_H_
 
-#include "./Alloc/alloc.h"
-#include "./Alloc/xNewDelete.h"
+#include "./MemOps/MemOps.h"
 #include "./Bamg/shared.h"
 #include "./Elements/elements.h"
+#include "./Enum/Enum.h"
 #include "./Exceptions/exceptions.h"
+#include "./io/io.h"
 #include "./Exp/exp.h"
 #include "./Matrix/matrix.h"
-#include "./MemOps/xMemCpy.h"
 #include "./Numerics/numerics.h"
 #include "./Sorting/sorting.h"
@@ -19,4 +19,5 @@
 #include "./Threads/issm_threads.h"
 #include "./TriMesh/trimesh.h"
+#include "./LatLong/latlong.h"
 
 #endif
Index: /issm/trunk/src/c/solutionsequences/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/solutionsequences/CMakeLists.txt	(revision 15396)
+++ /issm/trunk/src/c/solutionsequences/CMakeLists.txt	(revision 15396)
@@ -0,0 +1,16 @@
+# 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 15396)
+++ /issm/trunk/src/c/solutionsequences/convergence.cpp	(revision 15396)
@@ -0,0 +1,146 @@
+/*!\file: convergence.cpp
+ * \brief: figure out if convergence has been reached
+ */ 
+
+#include "../classes/classes.h"
+#include "../modules/modules.h"
+#include "../shared/shared.h"
+
+void convergence(bool* pconverged, Matrix<IssmDouble>* Kff,Vector<IssmDouble>* pf,Vector<IssmDouble>* uf,Vector<IssmDouble>* old_uf,Parameters* parameters){
+
+	/*output*/
+	bool converged=false;
+
+	/*intermediary*/
+	Vector<IssmDouble>* KU=NULL;
+	Vector<IssmDouble>* KUF=NULL;
+	Vector<IssmDouble>* KUold=NULL;
+	Vector<IssmDouble>* KUoldF=NULL;
+	Vector<IssmDouble>* duf=NULL;
+	IssmDouble ndu,nduinf,nu;
+	IssmDouble nKUF;
+	IssmDouble nKUoldF;
+	IssmDouble nF;
+	IssmDouble solver_residue,res;
+
+	/*convergence options*/
+	IssmDouble eps_res;
+	IssmDouble eps_rel;
+	IssmDouble eps_abs;
+	IssmDouble yts;
+
+	if(VerboseModule()) _printf0_("   checking convergence\n");
+
+	/*If uf is NULL in input, f-set is nil, model is fully constrained, therefore converged from 
+	 * the get go: */
+	if(uf->IsEmpty()){
+		*pconverged=true;
+		return;
+	}
+
+	/*get convergence options*/
+	parameters->FindParam(&eps_res,DiagnosticRestolEnum);
+	parameters->FindParam(&eps_rel,DiagnosticReltolEnum);
+	parameters->FindParam(&eps_abs,DiagnosticAbstolEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+
+	/*Display solver caracteristics*/
+	if (VerboseConvergence()){
+
+		//compute KUF = KU - F = K*U - F
+		KU=uf->Duplicate(); Kff->MatMult(uf,KU);
+		KUF=KU->Duplicate(); KU->Copy(KUF); KUF->AYPX(pf,-1.0);
+
+		//compute norm(KUF), norm(F) and residue
+		nKUF=KUF->Norm(NORM_TWO);
+		nF=pf->Norm(NORM_TWO);
+		solver_residue=nKUF/nF;
+		_printf0_("\n" << "   solver residue: norm(KU-F)/norm(F)=" << solver_residue << "\n");
+
+		//clean up
+		delete KU;
+		delete KUF;
+	}
+
+	/*Force equilibrium (Mandatory)*/
+
+	//compute K[n]U[n-1]F = K[n]U[n-1] - F
+	_assert_(uf); _assert_(Kff);
+	KUold=uf->Duplicate(); Kff->MatMult(old_uf,KUold);
+	KUoldF=KUold->Duplicate();KUold->Copy(KUoldF); KUoldF->AYPX(pf,-1.0);
+	nKUoldF=KUoldF->Norm(NORM_TWO);
+	nF=pf->Norm(NORM_TWO);
+	res=nKUoldF/nF;
+	if (xIsNan<IssmDouble>(res)){
+		_printf0_("norm nf = " << nF << "f and norm kuold = " << nKUoldF << "f\n");
+		_error_("mechanical equilibrium convergence criterion is NaN!");
+	}
+
+	//clean up
+	delete KUold;
+	delete KUoldF;
+
+	//print
+	if(res<eps_res){
+		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   mechanical equilibrium convergence criterion"<<res*100<< " < "<<eps_res*100<<" %\n");
+		converged=true;
+	}
+	else{ 
+		if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   mechanical equilibrium convergence criterion"<<res*100<<" > "<<eps_res*100<<" %\n");
+		converged=false;
+	}
+
+	/*Relative criterion (optional)*/
+	if (!xIsNan<IssmDouble>(eps_rel) || (VerboseConvergence())){
+
+		//compute norm(du)/norm(u)
+		duf=old_uf->Duplicate(); old_uf->Copy(duf); duf->AYPX(uf,-1.0);
+		ndu=duf->Norm(NORM_TWO); nu=old_uf->Norm(NORM_TWO);
+
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+
+		//clean up
+		delete duf;
+
+		//print
+		if (!xIsNan<IssmDouble>(eps_rel)){
+			if((ndu/nu)<eps_rel){
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " < " << eps_rel*100 << " %\n");
+			}
+			else{ 
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " > " << eps_rel*100 << " %\n");
+				converged=false;
+			}
+		}
+		else _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " %\n");
+
+	}
+
+	/*Absolute criterion (Optional) = max(du)*/
+	if (!xIsNan<IssmDouble>(eps_abs) || (VerboseConvergence())){
+
+		//compute max(du)
+		duf=old_uf->Duplicate(); old_uf->Copy(duf); duf->AYPX(uf,-1.0);
+		ndu=duf->Norm(NORM_TWO); nduinf=duf->Norm(NORM_INF);
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+
+		//clean up
+		delete duf;
+
+		//print
+		if (!xIsNan<IssmDouble>(eps_abs)){
+			if ((nduinf*yts)<eps_abs){
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " < " << eps_abs << " m/yr\n");
+			}
+			else{
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " > " << eps_abs << " m/yr\n");
+				converged=false;
+			}
+		}
+		else  _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " m/yr\n");
+
+	}
+
+	/*assign output*/
+	*pconverged=converged;
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp	(revision 15396)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp	(revision 15396)
@@ -0,0 +1,35 @@
+/*!\file: solutionsequence_adjoint_linear.cpp
+ * \brief: numerical core of linear solutions
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_adjoint_linear(FemModel* femmodel){
+	/*This is axactly the same solutionsequence as solutionsequence_linear except that Reduceloadfromgtofx and Mergesolutionfromftogx
+	 * use the flag "true" so that all spc are taken as 0*/
+
+	/*intermediary: */
+	Matrix<IssmDouble>*  Kff = NULL;
+	Matrix<IssmDouble>*  Kfs = NULL;
+	Vector<IssmDouble>*  ug  = NULL;
+	Vector<IssmDouble>*  uf  = NULL;
+	Vector<IssmDouble>*  pf  = NULL;
+	Vector<IssmDouble>*  df  = NULL;
+	Vector<IssmDouble>*  ys  = NULL;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->UpdateConstraintsx();
+
+	femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
+	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);
+	delete ug; delete uf;
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 15396)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 15396)
@@ -0,0 +1,207 @@
+/*!\file: solutionsequence_hydro_nonlinear.cpp
+ * \brief: core of the hydro solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_hydro_nonlinear(FemModel* femmodel){
+	/*solution : */
+	Vector<IssmDouble>* ug_sed=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>* ys=NULL; 
+	Vector<IssmDouble>* dug=NULL; 
+	Vector<IssmDouble>* old_ug=NULL; 
+	
+	Matrix<IssmDouble>* Kff=NULL;
+	Matrix<IssmDouble>* Kfs=NULL;
+	Vector<IssmDouble>* pf=NULL;
+	Vector<IssmDouble>* df=NULL;
+
+	bool       sedconverged,eplconverged,hydroconverged;
+	bool       isefficientlayer;
+	int        constraints_converged;
+	int        num_unstable_constraints;
+	int        sedcount,eplcount,hydrocount;
+	int        hydro_maxiter;
+	IssmDouble sediment_kmax,time;
+	IssmDouble eps_hyd;
+	IssmDouble ndu_sed,nu_sed;
+	IssmDouble ndu_epl,nu_epl;
+
+	/*Recover parameters: */
+	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);//FIXME
+	femmodel->parameters->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	femmodel->parameters->FindParam(&eps_hyd,HydrologydcRelTolEnum);
+	femmodel->parameters->FindParam(&time,TimeEnum);
+	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);
+	if(isefficientlayer) {
+		femmodel->SetCurrentConfiguration(HydrologyDCEfficientAnalysisEnum);
+		GetSolutionFromInputsx(&ug_epl, femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+	}
+
+	hydroconverged=false;
+	for(;;){
+		sedcount=1;
+		eplcount=1;
+		//save pointer to old velocity
+		delete ug_sed_main_iter;
+		ug_sed_main_iter=ug_sed;
+		if(isefficientlayer){
+			delete ug_epl_main_iter;
+			ug_epl_main_iter=ug_epl;
+		}
+
+		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);
+		femmodel->UpdateConstraintsx();
+		femmodel->parameters->SetParam(HydrologySedimentEnum,HydrologyLayerEnum);
+
+		/*Iteration on the sediment layer*/
+		sedconverged=false;
+		for(;;){
+			femmodel->HydrologyTransferx();
+			femmodel->SystemMatricesx(&Kff, &Kfs, &pf,&df, &sediment_kmax);
+			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 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);
+
+			if (!sedconverged){
+				if(VerboseConvergence()) _printf0_("   # Sediment unstable constraints = " << num_unstable_constraints << "\n");
+				if(num_unstable_constraints==0) sedconverged = true;
+				if (sedcount>=hydro_maxiter){
+					_error_("   maximum number of Sediment iterations (" << hydro_maxiter << ") exceeded");
+				}
+			}
+			sedcount++;
+
+			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);
+				break;
+			}
+		}
+
+		/*Second layer*/
+		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);
+			femmodel->HydrologyEPLupdateDomainx();
+			femmodel->parameters->SetParam(HydrologyEfficientEnum,HydrologyLayerEnum);
+			eplconverged = false;
+			/*Iteration on the EPL layer*/
+			for(;;){
+				femmodel->HydrologyTransferx();
+				femmodel->SystemMatricesx(&Kff, &Kfs, &pf,&df,NULL);
+				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);
+				femmodel->HydrologyEPLupdateDomainx();			
+				
+				if (!eplconverged){
+					if(VerboseConvergence()) _printf0_("   # EPL unstable constraints = " << num_unstable_constraints << "\n");
+					if(num_unstable_constraints==0) eplconverged = true;
+					if (eplcount>=hydro_maxiter){
+						_error_("   maximum number of EPL iterations (" << hydro_maxiter << ") exceeded");
+					}
+				}
+				eplcount++;
+
+				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);
+					break;
+				}
+			}
+		}
+		/*System convergence check*/
+		if(!hydroconverged){
+			//compute norm(du)/norm(u)
+			dug=ug_sed->Duplicate(); _assert_(dug);
+			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);
+			if (xIsNan<IssmDouble>(ndu_sed) || xIsNan<IssmDouble>(nu_sed)) _error_("Sed convergence criterion is NaN!");
+			if (!xIsNan<IssmDouble>(eps_hyd)){
+				if (!isefficientlayer){
+					if ((ndu_sed/nu_sed)<eps_hyd){
+						if(VerboseConvergence()) _printf0_(setw(50) << left << "   Converged after, " << hydrocount << " iterations \n");
+						hydroconverged=true;
+					}
+					else{ 
+						if(VerboseConvergence()) _printf0_(setw(50) << left << "   Sediment Convergence criterion:" << ndu_sed/nu_sed*100 << " > " << eps_hyd*100 << " %\n");
+						hydroconverged=false;
+					}
+				}
+				else{
+					dug=ug_epl->Duplicate();_assert_(dug); 
+					ug_epl_main_iter->Copy(dug);_assert_(ug_epl_main_iter); 
+					dug->AYPX(ug_epl,-1.0);
+					ndu_epl=dug->Norm(NORM_TWO); 
+					nu_epl=ug_epl_main_iter->Norm(NORM_TWO);
+
+					if (xIsNan<IssmDouble>(ndu_epl) || xIsNan<IssmDouble>(nu_epl)) _error_("EPL convergence criterion is NaN!");
+					if (ndu_epl==0.0 && nu_epl==0.0) nu_epl=1.0e-6; /*Hacking the case where the EPL is used but empty*/
+					if ((ndu_epl/nu_epl)<eps_hyd && (ndu_sed/nu_sed)<(eps_hyd*10)){
+						if (VerboseConvergence()) _printf0_(setw(50) << left << "   Converged after, " << hydrocount << " iterations \n");
+						hydroconverged=true;
+					}
+					else{ 
+						if(VerboseConvergence()) _printf0_(setw(50) << left << "   Sediment Convergence criterion:" << ndu_sed/nu_sed*100 << " aiming lower than " << eps_hyd*100 << " %\n");
+						if(VerboseConvergence()) _printf0_(setw(50) << left << "   EPL Convergence criterion:" << ndu_epl/nu_epl*100 << " aiming lower than " << eps_hyd*100 << " %\n");
+						hydroconverged=false;
+					}
+				}
+			}
+			else _printf0_(setw(50) << left << "   Convergence criterion:" << ndu_sed/nu_sed*100 << " %\n");
+			if (hydrocount>=hydro_maxiter){
+				_error_("   maximum number for hydrological global iterations (" << hydro_maxiter << ") exceeded");
+			}
+		}
+		hydrocount++;
+		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);
+
+	/*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;
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_linear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_linear.cpp	(revision 15396)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_linear.cpp	(revision 15396)
@@ -0,0 +1,39 @@
+/*!\file: solutionsequence_linear.cpp
+ * \brief: numerical core of linear solutions
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_linear(FemModel* femmodel){
+
+	/*intermediary: */
+	Matrix<IssmDouble>*  Kff = NULL;
+	Matrix<IssmDouble>*  Kfs = NULL;
+	Vector<IssmDouble>*  ug  = NULL;
+	Vector<IssmDouble>*  uf  = NULL;
+	Vector<IssmDouble>*  pf  = NULL;
+	Vector<IssmDouble>*  df  = NULL;
+	Vector<IssmDouble>*  ys  = NULL;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->UpdateConstraintsx();
+
+	femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
+	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+	Reduceloadx(pf, Kfs, ys); delete Kfs;
+	Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+	delete Kff; delete pf; delete df;
+//#ifdef  _HAVE_ADOLC_
+//        for (int i =0; i<uf->svector->M; ++i) {
+//          ADOLC_DUMP_MACRO(uf->svector->vector[i]);
+//        }
+//#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); 
+	delete ug;  
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp	(revision 15396)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp	(revision 15396)
@@ -0,0 +1,113 @@
+/*!\file: solutionsequence_nonlinear.cpp
+ * \brief: core of a non-linear solution, using fixed-point method 
+ */ 
+
+#include "./solutionsequences.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_newton(FemModel* femmodel){
+
+	/*intermediary: */
+	bool   converged;
+	int    count,newton;
+	IssmDouble kmax;
+	Matrix<IssmDouble>* Kff = NULL;
+	Matrix<IssmDouble>* Kfs    = NULL;
+	Matrix<IssmDouble>* Jff = NULL;
+	Vector<IssmDouble>* ug  = NULL;
+	Vector<IssmDouble>* old_ug = NULL;
+	Vector<IssmDouble>* uf  = NULL;
+	Vector<IssmDouble>* old_uf = NULL;
+	Vector<IssmDouble>* duf = NULL;
+	Vector<IssmDouble>* pf  = NULL;
+	Vector<IssmDouble>* pJf    = NULL;
+	Vector<IssmDouble>* df  = NULL;
+	Vector<IssmDouble>* ys  = NULL;
+
+	/*parameters:*/
+	int max_nonlinear_iterations;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&newton,DiagnosticIsnewtonEnum);
+	femmodel->UpdateConstraintsx();
+
+	count=1;
+	converged=false;
+
+	/*Start non-linear iteration using input velocity: */
+	GetSolutionFromInputsx(&ug,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	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);
+
+	for(;;){
+
+		delete old_ug;old_ug=ug;
+		delete old_uf;old_uf=uf;
+
+		/*Solver forward model*/
+		if(count==1 || newton==2){
+			femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
+			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);
+			delete old_ug;old_ug=ug;
+			delete old_uf;old_uf=uf;
+		}
+		uf=old_uf->Duplicate(); old_uf->Copy(uf);
+
+		/*Prepare next iteration using Newton's method*/
+		femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);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);
+
+		femmodel->CreateJacobianMatrixx(&Jff,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);
+
+		/*Check convergence*/
+		convergence(&converged,Kff,pf,uf,old_uf,femmodel->parameters); 
+		delete Kff; delete pf;
+		if(converged==true){	
+			bool max_iteration_state=false;
+			int tempStep=1;
+			IssmDouble tempTime=1.0;
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
+			break;
+		}
+		if(count>=max_nonlinear_iterations){
+			_printf0_("   maximum number of Newton iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
+			bool max_iteration_state=true;
+			int tempStep=1;
+			IssmDouble tempTime=1.0;
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
+			break;
+		}
+
+		count++;
+	}
+
+	if(VerboseConvergence()) _printf0_("\n   total number of iterations: " << count-1 << "\n");
+
+	/*clean-up*/
+	delete uf;
+	delete ug;
+	delete old_ug;
+	delete old_uf;
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp	(revision 15396)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp	(revision 15396)
@@ -0,0 +1,115 @@
+/*!\file: solutionsequence_nonlinear.cpp
+ * \brief: core of a non-linear solution, using fixed-point method 
+ */ 
+
+#include "./solutionsequences.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_nonlinear(FemModel* femmodel,bool conserve_loads){
+
+	/*intermediary: */
+	Matrix<IssmDouble>* Kff = NULL;
+	Matrix<IssmDouble>* Kfs = NULL;
+	Vector<IssmDouble>* ug  = NULL;
+	Vector<IssmDouble>* uf  = NULL;
+	Vector<IssmDouble>* old_uf = NULL;
+	Vector<IssmDouble>* pf  = NULL;
+	Vector<IssmDouble>* df  = NULL;
+	Vector<IssmDouble>* ys  = NULL;
+
+	Loads* savedloads=NULL;
+	bool converged;
+	int constraints_converged;
+	int num_unstable_constraints;
+	int count;
+
+	/*parameters:*/
+	int min_mechanical_constraints;
+	int max_nonlinear_iterations;
+	int configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->UpdateConstraintsx();
+
+	/*Were loads requested as output? : */
+	if(conserve_loads){
+		savedloads = static_cast<Loads*>(femmodel->loads->Copy());
+	}
+
+	count=1;
+	converged=false;
+
+	/*Start non-linear iteration using input velocity: */
+	GetSolutionFromInputsx(&ug, femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+	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);
+
+	for(;;){
+
+		//save pointer to old velocity
+		delete old_uf;old_uf=uf;
+		delete ug;
+
+		femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
+		Solverx(&uf, Kff, pf, old_uf, df, femmodel->parameters);
+		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
+
+		convergence(&converged,Kff,pf,uf,old_uf,femmodel->parameters); delete Kff; delete pf; delete df;
+		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);
+
+		ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		if(VerboseConvergence()) _printf0_("   number of unstable constraints: " << num_unstable_constraints << "\n");
+
+		//rift convergence
+		if (!constraints_converged) {
+			if (converged){
+				if (num_unstable_constraints <= min_mechanical_constraints) converged=true;
+				else converged=false;
+			}
+		}
+
+		/*Increase count: */
+		count++;
+		if(converged==true){
+			bool max_iteration_state=false;
+			int tempStep=1;
+			IssmDouble tempTime=1.0;
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
+			break;
+		}
+		if(count>=max_nonlinear_iterations){
+			_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);		
+			bool max_iteration_state=true;
+			int tempStep=1;
+			IssmDouble tempTime=1.0;
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
+			break;
+		}
+	}
+
+	if(VerboseConvergence()) _printf0_("\n   total number of iterations: " << count-1 << "\n");
+
+	/*clean-up*/
+	if(conserve_loads){
+		delete femmodel->loads;
+		femmodel->loads=savedloads;
+	}
+	delete uf;
+	delete ug;
+	delete old_uf;
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp	(revision 15396)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp	(revision 15396)
@@ -0,0 +1,100 @@
+/*!\file: solutionsequence_stokescoupling_nonlinear.cpp
+ * \brief: core of the coupling between stokes and macayealpattyn
+ */ 
+
+#include "./solutionsequences.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_stokescoupling_nonlinear(FemModel* femmodel,bool conserve_loads){
+
+	/*intermediary: */
+	Matrix<IssmDouble> *Kff_horiz    = NULL;
+	Matrix<IssmDouble> *Kfs_horiz    = NULL;
+	Vector<IssmDouble> *ug_horiz     = NULL;
+	Vector<IssmDouble> *uf_horiz     = NULL;
+	Vector<IssmDouble> *old_uf_horiz = NULL;
+	Vector<IssmDouble> *pf_horiz     = NULL;
+	Vector<IssmDouble> *df_horiz     = NULL;
+	Matrix<IssmDouble> *Kff_vert     = NULL;
+	Matrix<IssmDouble> *Kfs_vert     = NULL;
+	Vector<IssmDouble> *ug_vert      = NULL;
+	Vector<IssmDouble> *uf_vert      = NULL;
+	Vector<IssmDouble> *pf_vert      = NULL;
+	Vector<IssmDouble> *df_vert      = NULL;
+	Vector<IssmDouble> *ys           = NULL;
+	bool converged;
+	int  count;
+
+	/*parameters:*/
+	int  min_mechanical_constraints;
+	int  max_nonlinear_iterations;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
+	femmodel->UpdateConstraintsx();
+
+	count=1;
+	converged=false;
+
+	/*First get ug_horiz:*/
+	femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
+	GetSolutionFromInputsx(&ug_horiz, femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters);
+	Reducevectorgtofx(&uf_horiz, ug_horiz, femmodel->nodes,femmodel->parameters);
+
+	for(;;){
+
+		/*First diagnostic horiz:*/
+		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
+		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);
+		delete ug_horiz;
+
+		//save pointer to old velocity
+		delete old_uf_horiz; old_uf_horiz=uf_horiz;
+
+		/*solve: */
+		femmodel->SystemMatricesx(&Kff_horiz, &Kfs_horiz, &pf_horiz, &df_horiz, NULL);
+		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);
+
+		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->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+		/*solve: */
+		femmodel->SystemMatricesx(&Kff_vert, &Kfs_vert, &pf_vert,  &df_vert,NULL);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf_vert, Kfs_vert, ys); delete Kfs_vert;
+		Solverx(&uf_vert, Kff_vert, pf_vert, NULL, df_vert,femmodel->parameters); delete Kff_vert; delete pf_vert; delete df_vert;
+		Mergesolutionfromftogx(&ug_vert, uf_vert,ys,femmodel->nodes,femmodel->parameters);
+		delete uf_vert; 
+		delete ys; 
+		InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_vert);
+		delete ug_vert;
+
+		/*Increase count: */
+		count++;
+		if(converged==true)break;
+		if(count>=max_nonlinear_iterations){
+			_printf0_("   maximum number of iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
+			break;
+		}
+	}
+
+	/*clean-up*/
+	delete old_uf_horiz;
+	delete uf_horiz;
+	delete ug_horiz;
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 15396)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 15396)
@@ -0,0 +1,82 @@
+/*!\file: solutionsequence_thermal_nonlinear.cpp
+ * \brief: core of the thermal solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+void solutionsequence_thermal_nonlinear(FemModel* femmodel){
+
+	/*solution : */
+	Vector<IssmDouble>* tg=NULL; 
+	Vector<IssmDouble>* tf=NULL; 
+	Vector<IssmDouble>* tf_old=NULL; 
+	Vector<IssmDouble>* ys=NULL; 
+	IssmDouble melting_offset;
+
+	/*intermediary: */
+	Matrix<IssmDouble>* Kff=NULL;
+	Matrix<IssmDouble>* Kfs=NULL;
+	Vector<IssmDouble>* pf=NULL;
+	Vector<IssmDouble>* df=NULL;
+
+	bool converged;
+	int constraints_converged;
+	int num_unstable_constraints;
+	int count;
+	int thermal_penalty_threshold;
+	int thermal_maxiter;
+
+	/*parameters:*/
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&thermal_penalty_threshold,ThermalPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&thermal_maxiter,ThermalMaxiterEnum);
+
+	count=1;
+	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);
+	femmodel->UpdateConstraintsx();
+
+	for(;;){
+
+		femmodel->SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); delete Kfs; delete tf;
+		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);
+
+		ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+
+		if (!converged){
+			if(VerboseConvergence()) _printf0_("   #unstable constraints = " << num_unstable_constraints << "\n");
+			if (num_unstable_constraints <= thermal_penalty_threshold)converged=true;
+			if (count>=thermal_maxiter){
+				converged=true;
+				_printf0_("   maximum number of iterations (" << thermal_maxiter << ") exceeded\n"); 
+			}
+		}
+		count++;
+
+		InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,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);
+
+	/*Free ressources: */
+	delete tg;
+	delete tf;
+	delete tf_old;
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequences.h
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 15396)
+++ /issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 15396)
@@ -0,0 +1,25 @@
+/*
+ * solutionsequences.h: 
+ */
+
+#ifndef _SOLUTION_SEQUENCES_H_
+#define _SOLUTION_SEQUENCES_H_
+
+class FemModel;
+class Parameters;
+template <class doubletype> class Matrix;
+template <class doubletype> class Vector;
+#include "../shared/Numerics/types.h"
+
+void solutionsequence_thermal_nonlinear(FemModel* femmodel);
+void solutionsequence_hydro_nonlinear(FemModel* femmodel);
+void solutionsequence_nonlinear(FemModel* femmodel,bool conserve_loads);
+void solutionsequence_newton(FemModel* femmodel);
+void solutionsequence_stokescoupling_nonlinear(FemModel* femmodel,bool conserve_loads);
+void solutionsequence_linear(FemModel* femmodel);
+void solutionsequence_adjoint_linear(FemModel* femmodel);
+
+/*convergence*/
+void convergence(bool* pconverged, Matrix<IssmDouble>* K_ff,Vector<IssmDouble>* p_f,Vector<IssmDouble>* u_f,Vector<IssmDouble>* u_f_old,Parameters* parameters);
+
+#endif
Index: /issm/trunk/src/c/toolkits/ToolkitOptions.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/ToolkitOptions.cpp	(revision 15396)
+++ /issm/trunk/src/c/toolkits/ToolkitOptions.cpp	(revision 15396)
@@ -0,0 +1,98 @@
+/*! \file ToolkitOptions.cpp
+ * \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>
+#include "./ToolkitOptions.h"
+#include "../shared/Numerics/types.h"
+#include "../shared/Exceptions/exceptions.h"
+#include "../shared/MemOps/MemOps.h"
+
+void ToolkitOptions::Init(char* options){ /*{{{*/
+
+	/*First, avoid a leak: */
+	xDelete<char>(toolkitoptions);
+
+	/*copy options into toolkitoptions:*/
+	_assert_(options);
+	toolkitoptions= xNew<char>(strlen(options)+1); 
+	sprintf(toolkitoptions,   "%s",options);
+
+}/*}}}*/
+char* ToolkitOptions::GetToolkitType(){  /*{{{*/
+
+	/*Look for token: -toolkit, and return value:*/
+
+	return TokenValue(toolkitoptions,"toolkit");
+
+}/*}}}*/
+char* ToolkitOptions::GetToolkitOptionValue(const char* option){  /*{{{*/
+
+	return TokenValue(toolkitoptions,option);
+
+}/*}}}*/
+char* TokenValue(char* tokenlist,const char* target){ /*{{{*/
+
+	/*output:*/
+	char* value=NULL;
+
+	/*intermediary: */
+	char *token         = NULL;
+	char *tokenlistcopy = NULL;
+
+	/*First, because tokenizing destroys a string, copy what we have: */
+	_assert_(tokenlist);
+	tokenlistcopy= xNew<char>(strlen(tokenlist)+1); 
+	sprintf(tokenlistcopy,"%s",tokenlist);
+
+	/*Now go through list of tokens, and look for  target, return value: */
+	token=strtok(tokenlistcopy, " ");
+	while(token != NULL) {
+
+		/*Is this token starting with "-", if so, compare to our target: */
+		if (strncmp(token,"-",1)==0){
+			if (strcmp(token+1,target)==0){
+				/*Ok, we found our target. Get next token: */
+				token = strtok(NULL, " ");
+				/*This token could actually be another option start with "-", just be sure: */
+				if (strncmp(token,"-",1)==0){
+					/*ok, we hit another option, which means our target value is "":*/
+					value= xNew<char>(strlen("")+1); 
+					sprintf(value,"%s","");
+					continue;
+				}
+				else{
+					/*this token is the value we are looking for, copy: */
+					value= xNew<char>(strlen(token)+1); 
+					sprintf(value,"%s",token);
+				}
+			}
+			else{
+				/*we found the wrong target. Go to the next option: */
+				token = strtok(NULL, " ");
+				if (strncmp(token,"-",1)==0){
+					/*this is indeed an option, continue: */
+					continue;
+				}
+				else{
+					/*this is the value of the option, discard it: */
+				}
+			}
+		}
+		else _error_("token list should start with an option, not a value");
+
+		/*Get new token and continue*/
+		token = strtok(NULL, " ");
+	}
+
+	/*Clean up and return*/
+	xDelete<char>(tokenlistcopy);
+	return value;
+}
+/*}}}*/
Index: /issm/trunk/src/c/toolkits/ToolkitOptions.h
===================================================================
--- /issm/trunk/src/c/toolkits/ToolkitOptions.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/ToolkitOptions.h	(revision 15396)
@@ -0,0 +1,32 @@
+/* \file ToolkitOptions.h
+ * \brief  create a class with a static string of options, and static methods to access it
+ * This is a way of protecting access to the toolkit options, and to make it accessible everywhere
+ * in the code.
+ */
+
+#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 {
+
+	private:
+		static char* toolkitoptions;
+
+	public:
+		static void Init(char* options);
+		static char* GetToolkitType(void);
+		static char* GetToolkitOptionValue(const char* option);
+};
+
+char* TokenValue(char* tokenlist,const char* target);
+
+#endif  /* _TOOLKIT_OPTIONS_H */
Index: /issm/trunk/src/c/toolkits/adolc/AdolcEdf.h
===================================================================
--- /issm/trunk/src/c/toolkits/adolc/AdolcEdf.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/adolc/AdolcEdf.h	(revision 15396)
@@ -0,0 +1,32 @@
+/*
+ * adolc_edf.h
+ *
+ *  Created on: Jun 26, 2012
+ *      Author: utke
+ */
+
+#ifndef _ADOLC_EDF_H_
+#define _ADOLC_EDF_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+
+struct Adolc_edf {
+    ext_diff_fct *myEDF_for_solverx_p;
+    Adolc_edf() : myEDF_for_solverx_p(0) {}
+    inline friend std::ostream& operator << ( ostream&, const Adolc_edf& );
+};
+
+std::ostream& operator << ( std::ostream& out, const Adolc_edf& a) {
+    out << a.myEDF_for_solverx_p;
+    return out;
+}
+
+#endif
+
+#endif
Index: /issm/trunk/src/c/toolkits/adolc/adolcincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/adolc/adolcincludes.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/adolc/adolcincludes.h	(revision 15396)
@@ -0,0 +1,10 @@
+/* \file adolcincludes.h
+ * \brief all includes for ADOLC layer
+ */
+
+#ifndef _ADOLC_PATCHES_INCLUDES_H_
+#define _ADOLC_PATCHES_INCLUDES_H_
+
+#include "./AdolcEdf.h"
+
+#endif
Index: /issm/trunk/src/c/toolkits/gsl/DenseGslSolve.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/gsl/DenseGslSolve.cpp	(revision 15396)
+++ /issm/trunk/src/c/toolkits/gsl/DenseGslSolve.cpp	(revision 15396)
@@ -0,0 +1,246 @@
+/*!\file DenseGslSolve.cpp
+ * \brief: solve dense matrix system with GSL library
+ */
+
+/*Header files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include "../../classes/Params/GenericParam.h"
+#include "../../classes/Params/Parameters.h"
+#include "../adolc/adolcincludes.h"
+#include "./gslincludes.h"
+
+#ifdef _HAVE_GSL_
+#include <gsl/gsl_linalg.h>
+#endif
+
+/*}}}*/
+
+void DenseGslSolve(IssmPDouble** pX,IssmPDouble* A,IssmPDouble* B, int n){ /*{{{*/
+
+	/*Intermediary: */
+	IssmPDouble *X  = xNew<IssmPDouble>(n);
+	SolverxSeq(X,A,B,n);
+
+	/*allocate output pointers: */
+	*pX=X;
+}
+/*}}}*/
+void DenseGslSolve(/*output*/ IssmPDouble** px,/*stiffness matrix:*/ IssmPDouble* Kff, int Kff_M, int Kff_N, /*right hand side load vector: */ IssmPDouble* pf, int pf_M, Parameters* parameters){ /*{{{*/
+
+	/*Intermediary: */
+
+	if(Kff_N!=pf_M)_error_("Right hand side vector of size " << pf_M << ", when matrix is of size " << Kff_M << "-" << Kff_N << " !");
+	if(Kff_M!=Kff_N)_error_("Stiffness matrix should be square!");
+
+	IssmPDouble *x  = xNew<IssmPDouble>(Kff_N);
+	SolverxSeq(x,Kff,pf,Kff_N);
+
+	/*allocate output pointers: */
+	*px=x;
+}
+/*}}}*/
+void SolverxSeq(IssmPDouble *X, IssmPDouble *A, IssmPDouble *B,int n){ /*{{{*/
+#ifdef _HAVE_GSL_
+	/*GSL Matrices and vectors: */
+	int              s;
+	gsl_matrix_view  a;
+	gsl_vector_view  b,x;
+	gsl_permutation *p = NULL;
+//	for (int i=0; i<n*n; ++i) std::cout << "SolverxSeq A["<< i << "]=" << A[i] << std::endl;
+//	for (int i=0; i<n; ++i) std::cout << "SolverxSeq b["<< i << "]=" << B[i] << std::endl;
+	/*A will be modified by LU decomposition. Use copy*/
+	double* Acopy = xNew<double>(n*n);
+	xMemCpy(Acopy,A,n*n);
+
+	/*Initialize gsl matrices and vectors: */
+	a = gsl_matrix_view_array (Acopy,n,n);
+	b = gsl_vector_view_array (B,n);
+	x = gsl_vector_view_array (X,n);
+
+	/*Run LU and solve: */
+	p = gsl_permutation_alloc (n);
+	gsl_linalg_LU_decomp (&a.matrix, p, &s);
+	gsl_linalg_LU_solve (&a.matrix, p, &b.vector, &x.vector);
+
+	/*Clean up and assign output pointer*/
+	xDelete(Acopy);
+	gsl_permutation_free(p);
+#endif
+}
+/*}}}*/
+
+#ifdef _HAVE_ADOLC_
+int EDF_for_solverx(int n, IssmPDouble *x, int m, IssmPDouble *y){ /*{{{*/
+	SolverxSeq(y,x, x+m*m, m); // x is where the matrix starts, x+m*m is where the right-hand side starts
+	return 0;
+} /*}}}*/
+int EDF_fos_forward_for_solverx(int n, IssmPDouble *inVal, IssmPDouble *inDeriv, int m, IssmPDouble *outVal, IssmPDouble *outDeriv) { /*{{{*/
+#ifdef _HAVE_GSL_
+	//  for (int i=0; i<m*m; ++i) std::cout << "EDF_fos_forward_for_solverx A["<< i << "]=" << inVal[i] << std::endl;
+	//  for (int i=0; i<m; ++i) std::cout << "EDF_fos_forward_for_solverx b["<< i << "]=" << inVal[i+m*m] << std::endl;
+	// the matrix will be modified by LU decomposition. Use gsl_A copy
+	double* Acopy = xNew<double>(m*m);
+	xMemCpy(Acopy,inVal,m*m);
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
+	gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int  signPerm;
+	// factorize
+	gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
+	gsl_vector *gsl_x_p = gsl_vector_alloc (m);
+	// solve for the value
+	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
+	/*Copy result*/
+	xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
+	gsl_vector_free(gsl_x_p);
+	//  for (int i=0; i<m; ++i) std::cout << "EDF_fos_forward_for_solverx x["<< i << "]=" << outVal[i] << std::endl;
+	// solve for the derivatives acc. to A * dx = r  with r=db - dA * x
+	// compute the RHS
+	double* r=xNew<double>(m);
+	for (int i=0; i<m; i++) {
+		r[i]=inDeriv[m*m+i]; // this is db[i]
+		for (int j=0;j<m; j++) {
+			r[i]-=inDeriv[i*m+j]*outVal[j]; // this is dA[i][j]*x[j]
+		}
+	}
+	gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
+	gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
+	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
+	xMemCpy(outDeriv,gsl_vector_ptr(gsl_dx_p,0),m);
+	gsl_vector_free(gsl_dx_p);
+	xDelete(r);
+	gsl_permutation_free(perm_p);
+	xDelete(Acopy);
+#endif
+	return 0;
+} /*}}}*/
+int EDF_fov_forward_for_solverx(int n, IssmPDouble *inVal, int directionCount, IssmPDouble **inDeriv, int m, IssmPDouble *outVal, IssmPDouble **outDeriv) { /*{{{*/
+#ifdef _HAVE_GSL_
+	// the matrix will be modified by LU decomposition. Use gsl_A copy
+	double* Acopy = xNew<double>(m*m);
+	xMemCpy(Acopy,inVal,m*m);
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
+	gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int  signPerm;
+	// factorize
+	gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
+	gsl_vector *gsl_x_p = gsl_vector_alloc (m);
+	// solve for the value
+	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
+	/*Copy result*/
+	xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
+	gsl_vector_free(gsl_x_p);
+	// solve for the derivatives acc. to A * dx = r  with r=db - dA * x
+	double* r=xNew<double>(m);
+	gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
+	for (int dir=0;dir<directionCount;++dir) {
+		// compute the RHS
+		for (int i=0; i<m; i++) {
+			r[i]=inDeriv[m*m+i][dir]; // this is db[i]
+			for (int j=0;j<m; j++) {
+				r[i]-=inDeriv[i*m+j][dir]*outVal[j]; // this is dA[i][j]*x[j]
+			}
+		}
+		gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
+		gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
+		// reuse r
+		xMemCpy(r,gsl_vector_ptr(gsl_dx_p,0),m);
+		for (int i=0; i<m; i++) {
+			outDeriv[i][dir]=r[i];
+		}
+	}
+	gsl_vector_free(gsl_dx_p);
+	xDelete(r);
+	gsl_permutation_free(perm_p);
+	xDelete(Acopy);
+#endif
+	return 0;
+}
+/*}}}*/
+int EDF_fos_reverse_for_solverx(int m, double *dp_U, int n, double *dp_Z, double* dp_x, double* dp_y) { /*{{{*/
+	// copy to transpose the matrix
+	double* transposed=xNew<double>(m*m);
+	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) transposed[j*m+i]=dp_x[i*m+j];
+	gsl_matrix_view aTransposed = gsl_matrix_view_array (transposed,m,m);
+	// the adjoint of the solution is our right-hand side
+	gsl_vector_view x_bar=gsl_vector_view_array(dp_U,m);
+	// the last m elements of dp_Z representing the adjoint of the right-hand side we want to compute:
+	gsl_vector_view b_bar=gsl_vector_view_array(dp_Z+m*m,m);
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int permSign;
+	gsl_linalg_LU_decomp (&aTransposed.matrix, perm_p, &permSign);
+	gsl_linalg_LU_solve (&aTransposed.matrix, perm_p, &x_bar.vector, &b_bar.vector);
+	// now do the adjoint of the matrix
+	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) dp_Z[i*m+j]-=dp_Z[m*m+i]*dp_y[j];
+	gsl_permutation_free(perm_p);
+	xDelete(transposed);
+	return 0;
+}
+/*}}}*/
+int EDF_fov_reverse_for_solverx(int m, int p, double **dpp_U, int n, double **dpp_Z, double* dp_x, double* dp_y) { /*{{{*/
+	// copy to transpose the matrix
+	double* transposed=xNew<double>(m*m);
+	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) transposed[j*m+i]=dp_x[i*m+j];
+	gsl_matrix_view aTransposed = gsl_matrix_view_array (transposed,m,m);
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int permSign;
+	gsl_linalg_LU_decomp (&aTransposed.matrix, perm_p, &permSign);
+	for (int weightsRowIndex=0;weightsRowIndex<p;++weightsRowIndex) {
+		// the adjoint of the solution is our right-hand side
+		gsl_vector_view x_bar=gsl_vector_view_array(dpp_U[weightsRowIndex],m);
+		// the last m elements of dp_Z representing the adjoint of the right-hand side we want to compute:
+		gsl_vector_view b_bar=gsl_vector_view_array(dpp_Z[weightsRowIndex]+m*m,m);
+		gsl_linalg_LU_solve (&aTransposed.matrix, perm_p, &x_bar.vector, &b_bar.vector);
+		// now do the adjoint of the matrix
+		for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) dpp_Z[weightsRowIndex][i*m+j]-=dpp_Z[weightsRowIndex][m*m+i]*dp_y[j];
+	}
+	gsl_permutation_free(perm_p);
+	xDelete(transposed);
+	return 0;
+}
+/*}}}*/
+void DenseGslSolve(/*output*/ IssmDouble** px,/*stiffness matrix:*/ IssmDouble* Kff, int Kff_M, int Kff_N, /*right hand side load vector: */ IssmDouble* pf, int pf_M, Parameters* parameters){ /*{{{*/
+
+	/*Intermediary: */
+
+	if(Kff_N!=pf_M)_error_("Right hand side vector of size " << pf_M << ", when matrix is of size " << Kff_M << "-" << Kff_N << " !");
+	if(Kff_M!=Kff_N)_error_("Stiffness matrix should be square!");
+
+	ensureContiguousLocations(Kff_N);
+	IssmDouble *x  = xNew<IssmDouble>(Kff_N);
+
+	SolverxSeq(x,Kff,pf,Kff_N,parameters);
+
+	/*allocate output pointers: */
+	*px=x;
+}
+/*}}}*/
+void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters){/*{{{*/
+	// pack inputs to conform to the EDF-prescribed interface
+        // ensure a contiguous block of locations:
+        ensureContiguousLocations(n*(n+1));
+        IssmDouble*  adoubleEDFin=xNew<IssmDouble>(n*(n+1));  // packed inputs, i.e. matrix and right hand side
+        for(int i=0; i<n*n;i++)adoubleEDFin[i]    =A[i];      // pack matrix
+        for(int i=0; i<n;  i++)adoubleEDFin[i+n*n]=B[i];      // pack the right hand side
+        IssmPDouble* pdoubleEDFin=xNew<IssmPDouble>(n*(n+1)); // provide space to transfer inputs during call_ext_fct
+	IssmPDouble* pdoubleEDFout=xNew<IssmPDouble>(n);           // provide space to transfer outputs during call_ext_fct
+	// call the wrapped solver through the registry entry we retrieve from parameters
+	call_ext_fct(dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
+	             n*(n+1), pdoubleEDFin, adoubleEDFin,
+	             n, pdoubleEDFout,X);
+	// for(int i=0; i<n;  i++) {ADOLC_DUMP_MACRO(X[i]);}
+	xDelete(adoubleEDFin);
+	xDelete(pdoubleEDFin);
+	xDelete(pdoubleEDFout);
+}
+/*}}}*/
+#endif
Index: /issm/trunk/src/c/toolkits/gsl/gslincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/gsl/gslincludes.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/gsl/gslincludes.h	(revision 15396)
@@ -0,0 +1,37 @@
+/* \file gslsincludes.h
+ * \brief all includes for GSL layer
+ */
+
+#ifndef _GSL_INCLUDES_H_
+#define _GSL_INCLUDES_H_
+
+/*{{{*/
+#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"
+/*}}}*/
+
+template <class doubletype> class IssmVec;
+template <class doubletype> class IssmMat;
+class Parameters;
+
+void DenseGslSolve(IssmPDouble** pX,IssmPDouble* A,IssmPDouble* B, int n);
+void DenseGslSolve(IssmDouble** px, IssmDouble* Kff,int Kff_M, int Kff_N, IssmDouble* pf, int pf_M, Parameters* parameters);
+
+void SolverxSeq(IssmPDouble *X, IssmPDouble *A, IssmPDouble *B,int n);
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters);
+// call back functions:
+ADOLC_ext_fct EDF_for_solverx;
+ADOLC_ext_fct_fos_forward EDF_fos_forward_for_solverx;
+ADOLC_ext_fct_fos_reverse EDF_fos_reverse_for_solverx;
+ADOLC_ext_fct_fov_forward EDF_fov_forward_for_solverx;
+ADOLC_ext_fct_fov_reverse EDF_fov_reverse_for_solverx;
+#endif
+
+#endif
Index: /issm/trunk/src/c/toolkits/issm/Bucket.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/Bucket.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/Bucket.h	(revision 15396)
@@ -0,0 +1,242 @@
+/*!\file Bucket.h
+ * \brief: header file for Bucket object
+ */
+
+#ifndef _BUCKET_H
+#define _BUCKET_H
+
+/*Headers:*/
+/*{{{*/
+#include "../../datastructures/datastructures.h"
+#include "../../shared/shared.h"
+#include "../toolkitsenums.h"
+/*}}}*/
+
+/*how many MPI_Isend requests does it take to transfer the contents of a bucket to another cpu?*/
+#define MATRIXBUCKETSIZEOFREQUESTS 7 
+#define VECTORBUCKETSIZEOFREQUESTS 5 
+typedef enum {VECTOR_BUCKET, MATRIX_BUCKET} BucketType;
+template <class doubletype> class Bucket: public Object{
+
+	private: 
+		int type; //either a VECTOR_BUCKET or MATRIX_BUCKET
+		int m,n; /*size of local matrix we are storing*/
+		/*row and column indices of the matrix we are storing*/
+		int* idxm;
+		int* idxn; 
+		doubletype* values; /*local matrix*/
+		InsMode mode; /*mode of insertion for this bucket*/
+
+	public: 
+
+		/*constructors, destructors: */
+		Bucket(){ /*{{{*/
+			this->Initialize();
+		} /*}}}*/
+		Bucket(int min,int* idxmin,int nin,int* idxnin,doubletype* valuesin,InsMode modein){ /*{{{*/
+
+			this->Initialize();
+
+			this->type=MATRIX_BUCKET;
+			this->m=min;
+			this->n=nin;
+			this->mode=modein;
+			if(this->m){
+				this->idxm=xNew<int>(this->m); 
+				xMemCpy(this->idxm,idxmin,this->m);
+			}
+			if(this->n){
+				this->idxn=xNew<int>(this->n); 
+				xMemCpy(this->idxn,idxnin,this->n);
+			}
+			if(this->m*this->n){
+				this->values=xNew<doubletype>(this->n*this->m);
+				xMemCpy(this->values,valuesin,this->n*this->m);
+			}
+		} /*}}}*/
+		Bucket(int min,int* idxmin,doubletype* valuesin,InsMode modein){ /*{{{*/ 
+			this->Initialize();
+
+			this->type=VECTOR_BUCKET; 
+			this->m=min;
+			this->mode=modein;
+			if(this->m){
+				this->idxm=xNew<int>(this->m); 
+				xMemCpy(this->idxm,idxmin,this->m);
+
+				this->values=xNew<doubletype>(this->m);
+				xMemCpy(this->values,valuesin,this->m);
+			}
+		} /*}}}*/
+		~Bucket(){ /*{{{*/
+			xDelete<int>(idxm);
+			xDelete<int>(idxn);
+			xDelete<doubletype>(values);
+		} /*}}}*/
+		void Initialize(void){ /*{{{*/
+
+			this->type=0;
+			this->m=0;
+			this->n=0;
+			this->idxm=NULL;
+			this->idxn=NULL;
+			this->values=NULL;
+			mode=INS_VAL;
+
+		} /*}}}*/
+
+		/*object virtual functions definitions:*/
+		void    Echo(){ /*{{{*/
+			_printf_("Bucket echo (cpu #: "<<IssmComm::GetRank()<<")\n");
+			_printf_("bucket type: " << type << "\n");
+			_printf_("num rows: "<<this->m<<" num cols: "<<this->n << "\n");
+		} /*}}}*/
+		void    DeepEcho(){ /*{{{*/
+			int i,j;
+
+			_printf_("Bucket echo (cpu #: "<<IssmComm::GetRank()<<")\n");
+			_printf_("bucket type: " << type << "\n");
+			_printf_("num rows: "<<this->m<<" num cols: "<<this->n << "\n");
+			if(type==MATRIX_BUCKET){
+				for (i=0;i<this->m;i++){
+					_printf_("row "<<this->idxm[i]<<", column indices: \n");
+					for (j=0;j<this->n;j++){
+						_printf_(" "<<this->idxn[j] << "\n");
+					}
+					_printf_("values: \n");
+					for (j=0;j<this->n;j++){
+						_printf_(" "<<this->values[m*i+j] << "\n");
+					}
+				}
+			}
+			else if(type==VECTOR_BUCKET){
+				for (i=0;i<this->m;i++){
+					_printf_("row "<<this->idxm[i]<<", value " << this->values[i] << "\n");
+				}
+			}
+			else _error_("unknown type of bucket!");
+		}
+		/*}}}*/
+		int     Id(){ /*{{{*/
+			return -1;
+		} /*}}}*/
+		int     ObjectEnum(){ /*{{{*/
+			return -1;
+		} /*}}}*/
+		Object *copy()        {/*{{{*/
+			_error_("Not implemented yet (similar to Elements)"); };
+		/*}}}*/
+
+		/*specific routines of Bucket: */
+		void SpawnBucketsPerCpu(DataSet* bucketsofcpu_i,int rank_i,int* rowranks){ /*{{{*/
+
+			int i,j;
+
+			/*go through our idxm index of rows this bucket owns, and spawn buckets  
+			 *if these rows belong to cpu rank_i. Use rowranks to determine this.*/
+			for(i=0;i<m;i++){
+				if (rowranks[idxm[i]]==rank_i){
+					/*This row belongs to cpu rank_i, so spawn a bucket with this row, and add it to the bucketsofcpu_i dataset: */
+					if(type==MATRIX_BUCKET){
+						bucketsofcpu_i->AddObject(new Bucket(1,idxm+i,n,idxn,values+n*i,mode));
+					}
+					else{
+						bucketsofcpu_i->AddObject(new Bucket(1,idxm+i,values+i,mode));
+					}
+				}
+			}
+
+		};
+		/*}}}*/
+		int BucketType(void){ /*{{{*/
+
+			return type;
+		};
+		/*}}}*/
+		void Marshall(int** prow_indices_forcpu,int** pcol_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu){ /*{{{*/
+
+			/*intermediary: */
+			int         i;
+			int         j;
+
+			/*buffers: */
+			int        *row_indices_forcpu = NULL;
+			int        *col_indices_forcpu = NULL;
+			doubletype *values_forcpu      = NULL;
+			int        *modes_forcpu       = NULL;
+
+			/*initialize buffers: */
+			row_indices_forcpu=*prow_indices_forcpu;
+			col_indices_forcpu=*pcol_indices_forcpu;
+			values_forcpu=*pvalues_forcpu;
+			modes_forcpu=*pmodes_forcpu;
+
+			/*fill buffers with out values and indices and modes: */
+			for(i=0;i<m;i++){
+				for(j=0;j<n;j++){
+					row_indices_forcpu[i*n+j]=idxm[i];
+					col_indices_forcpu[i*n+j]=idxn[j];
+					values_forcpu[i*n+j]=values[i*n+j];
+					modes_forcpu[i*n+j]=mode;
+				}
+			}
+
+			/*increment buffer for next Bucket who will marshall his data: */
+			row_indices_forcpu+=(m*n);
+			col_indices_forcpu+=(m*n);
+			values_forcpu+=(m*n);
+			modes_forcpu+=(m*n);
+
+			/*output modified buffers: */
+			*prow_indices_forcpu=row_indices_forcpu;
+			*pcol_indices_forcpu=col_indices_forcpu;
+			*pvalues_forcpu=values_forcpu;
+			*pmodes_forcpu=modes_forcpu;
+		};
+		/*}}}*/
+		void Marshall(int** prow_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu){ /*{{{*/
+
+			/*intermediary: */
+			int         i;
+
+			/*buffers: */
+			int        *row_indices_forcpu = NULL;
+			doubletype *values_forcpu      = NULL;
+			int        *modes_forcpu       = NULL;
+
+			/*initialize buffers: */
+			row_indices_forcpu=*prow_indices_forcpu;
+			values_forcpu=*pvalues_forcpu;
+			modes_forcpu=*pmodes_forcpu;
+
+			/*fill buffers with out values and indices and modes: */
+			for(i=0;i<m;i++){
+				row_indices_forcpu[i]=idxm[i];
+				values_forcpu[i]=values[i];
+				modes_forcpu[i]=mode;
+			}
+
+			/*increment buffer for next Bucket who will marshall his data: */
+			row_indices_forcpu+=m;
+			values_forcpu+=m;
+			modes_forcpu+=m;
+
+			/*output modified buffers: */
+			*prow_indices_forcpu=row_indices_forcpu;
+			*pvalues_forcpu=values_forcpu;
+			*pmodes_forcpu=modes_forcpu;
+		};
+		/*}}}*/
+		int MarshallSize(void){ /*{{{*/
+
+			if(type==MATRIX_BUCKET){
+				return m*n;
+			}
+			else{
+				return m;
+			}
+		};
+		/*}}}*/
+};
+
+#endif  /* _BUCKET_H */
Index: /issm/trunk/src/c/toolkits/issm/IssmAbsMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmAbsMat.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmAbsMat.h	(revision 15396)
@@ -0,0 +1,59 @@
+/*!\file:  IssmAbsMat.h
+ * \brief Main abstract class for the ISSM matrices.  This abstract class defines the pure virtual
+ * functions that each of its descendants need to implement, such as contructors, destructors, as well
+ * as matrix specific routines, such as SetValue, Assemple, MatMult, etc ...
+ * Descendants include among others:
+ * IssmDenseMat and IssmMpiDenseMat
+ *
+ */ 
+
+#ifndef _ISSM_ABS_MAT_H_
+#define _ISSM_ABS_MAT_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../toolkitsenums.h"
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create Matrices that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  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)
+*/
+
+template <class doubletype> class IssmAbsVec;
+class Parameters;
+
+template <class doubletype> 
+class IssmAbsMat{
+
+	public:
+
+		/*IssmAbsMat constructors, destructors*/
+		virtual ~IssmAbsMat(){};
+
+		/*Functionality: */
+		virtual void Echo(void)=0;
+		virtual void Assemble(void)=0;
+		virtual doubletype Norm(NormMode mode)=0;
+		virtual void GetSize(int* pM,int* pN)=0;
+		virtual void GetLocalSize(int* pM,int* pN)=0;
+		virtual void MatMult(IssmAbsVec<doubletype>* X,IssmAbsVec<doubletype>* AX)=0;
+		virtual IssmAbsMat<doubletype>* Duplicate(void)=0;
+		virtual doubletype* ToSerial(void)=0;
+		virtual void SetValues(int m,int* idxm,int n,int* idxn,doubletype* values,InsMode mode)=0;
+		virtual void Convert(MatrixType type)=0;
+		#ifndef _HAVE_WRAPPERS_
+		virtual IssmAbsVec<IssmDouble>* Solve(IssmAbsVec<IssmDouble>* pf, Parameters* parameters)=0;
+		#endif
+};
+
+#endif //#ifndef _ISSM_ABS_MAT_H_
Index: /issm/trunk/src/c/toolkits/issm/IssmAbsVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmAbsVec.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmAbsVec.h	(revision 15396)
@@ -0,0 +1,59 @@
+/*!\file:  IssmAbsVec.h
+ * \brief Main abstract class for the ISSM vectors.  This abstract class defines the pure virtual
+ * functions that each of its descendants need to implement, such as contructors, destructors, as well
+ * as matrix specific routines, such as SetValue, Assemple, VecMult, etc ...
+ * Descendants include among others:
+ *	  IssmSeqVec and IssmMpiVec
+ *
+ */ 
+
+#ifndef _ISSM_ABS_VEC_H_
+#define _ISSM_ABS_VEC_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../toolkitsenums.h"
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create Vectors that hold
+  IssmDouble* vector or IssmPDouble* vector. 
+  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)
+*/
+template <class doubletype> 
+class IssmAbsVec{
+
+	public:
+
+		/*IssmAbsVec constructors, destructors*/
+		virtual ~IssmAbsVec(){};
+
+		/*IssmAbsVec specific routines*/
+		virtual void Echo(void)=0;
+		virtual void Assemble(void)=0;
+		virtual void SetValues(int ssize, int* list, doubletype* values, InsMode mode)=0;
+		virtual void SetValue(int dof, doubletype value, InsMode mode)=0;
+		virtual void GetValue(doubletype* pvalue,int dof)=0;
+		virtual void GetSize(int* pM)=0;
+		virtual void GetLocalSize(int* pM)=0;
+		virtual IssmAbsVec<doubletype>* Duplicate(void)=0;
+		virtual void Set(doubletype value)=0;
+		virtual void AXPY(IssmAbsVec* X, doubletype a)=0;
+		virtual void AYPX(IssmAbsVec* X, doubletype a)=0;
+		virtual doubletype* ToMPISerial(void)=0;
+		virtual void Copy(IssmAbsVec* to)=0;
+		virtual doubletype Norm(NormMode mode)=0;
+		virtual void Scale(doubletype scale_factor)=0;
+		virtual doubletype Dot(IssmAbsVec* input)=0;
+		virtual void PointwiseDivide(IssmAbsVec* x,IssmAbsVec* y)=0;
+};
+
+#endif //#ifndef _ISSM_ABS_VEC_H_
Index: /issm/trunk/src/c/toolkits/issm/IssmDenseMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmDenseMat.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmDenseMat.h	(revision 15396)
@@ -0,0 +1,287 @@
+/*!\file:  IssmDenseMat.h
+ * \brief implementation of an ISSM matrix which run serially (1 cpu only), which is made of a fully dense 
+ * matrix. Internally, this dense matrix is just a linear buffer of type doubletype. 
+ * This object needs to answer the API defined by the virtual functions in IssmAbsMat, 
+ * and the contructors required by IssmMat (see IssmMat.h)
+ */ 
+
+#ifndef _ISSM_DENSE_MAT_H_
+#define _ISSM_DENSE_MAT_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./IssmSeqVec.h"
+#include "../../shared/shared.h"
+#include "../gsl/gslincludes.h"
+
+#include <math.h>
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create Matrices that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  Such matrices would be useful for use without or with the matlab or python
+  interface (which do not care for IssmDouble types, but only rely on
+  IssmPDouble types)*/
+
+template <class doubletype> class IssmAbsVec;
+template <class doubletype> class IssmAbsMat;
+template <class doubletype> class IssmSeqVec;
+
+template <class doubletype> 
+class IssmDenseMat: public IssmAbsMat<doubletype>{
+
+	public:
+
+		int M,N; 
+		doubletype* matrix;  /*here, doubletype is either IssmDouble or IssmPDouble*/
+
+		/*IssmDenseMat constructors, destructors*/
+		/*IssmDenseMat(){{{*/
+		IssmDenseMat(){
+
+			this->M=0;
+			this->N=0;
+			this->matrix=NULL;
+		}
+		/*}}}*/
+		/*IssmDenseMat(int M,int N){{{*/
+		IssmDenseMat(int pM,int pN){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*IssmDenseMat(int M,int N, doubletype sparsity){{{*/
+		IssmDenseMat(int pM,int pN, doubletype sparsity){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*IssmDenseMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
+		IssmDenseMat(int m,int n,int pM,int pN,int* d_nnz,int* o_nnz){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(pM*pN) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*IssmDenseMat(doubletype* serial_mat,int M,int N,doubletype sparsity){{{*/
+		IssmDenseMat(doubletype* serial_mat,int pM,int pN,doubletype sparsity){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N){
+				this->matrix=xNewZeroInit<doubletype>(pM*pN);
+				xMemCpy<doubletype>(this->matrix,serial_mat,pM*pN);
+			}
+
+		}
+		/*}}}*/
+		/*IssmDenseMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
+		IssmDenseMat(int pM,int pN, int connectivity,int numberofdofspernode){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*~IssmDenseMat(){{{*/
+		~IssmDenseMat(){
+
+			xDelete<doubletype>(this->matrix);
+			M=0;
+			N=0;
+		}
+		/*}}}*/
+
+		/*IssmAbsMat virtual functions*/
+		/*Echo{{{*/
+		void Echo(void){
+
+			int i,j;
+			_printf_("IssmDenseMat size " << this->M << "-" << this->N << "\n");
+			for(i=0;i<M;i++){
+				for(j=0;j<N;j++){
+					_printf_(this->matrix[N*i+j] << " ");
+				}
+				_printf_("\n");
+			}
+		}
+		/*}}}*/
+		/*Assemble{{{*/
+		void Assemble(void){
+
+			/*do nothing*/
+
+		}
+		/*}}}*/
+		/*Norm{{{*/
+		doubletype Norm(NormMode mode){
+
+			doubletype norm;
+			doubletype absolute;
+			int i,j;
+
+			switch(mode){
+				case NORM_INF:
+					norm=0;
+					for(i=0;i<this->M;i++){
+						absolute=0;
+						for(j=0;j<this->N;j++){
+							absolute+=fabs(this->matrix[N*i+j]);
+						}
+						norm=max(norm,absolute);
+					}
+					return norm;
+					break; 
+				case NORM_FROB:
+					norm=0;
+					for(i=0;i<this->M;i++){
+						for(j=0;j<this->N;j++){
+							norm+=pow(this->matrix[N*i+j],2);
+						}
+					}
+					return sqrt(norm);
+					break; 
+
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		/*GetSize{{{*/
+		void GetSize(int* pM,int* pN){
+
+			*pM=this->M;
+			*pN=this->N;
+
+		}
+		/*}}}*/
+		/*GetLocalSize{{{*/
+		void GetLocalSize(int* pM,int* pN){
+
+			*pM=this->M;
+			*pN=this->N;
+
+		}
+		/*}}}*/
+		/*MatMult{{{*/
+		void MatMult(IssmAbsVec<doubletype>* Xin,IssmAbsVec<doubletype>* AXin){
+
+			/*We assume that the vectors coming in are of compatible type: */
+			int i,j;
+			int XM,AXM;
+			doubletype dummy;
+			IssmSeqVec<doubletype>* X=NULL;
+			IssmSeqVec<doubletype>* AX=NULL;
+
+			/*downcast X and AX: */
+			X=(IssmSeqVec<doubletype>*)Xin;
+			AX=(IssmSeqVec<doubletype>*)AXin;
+
+			/*Some checks first: */
+			X->GetSize(&XM);
+			AX->GetSize(&AXM);
+
+			if(M!=AXM)_error_("A and AX should have the same number of rows!");
+			if(N!=XM)_error_("A and X should have the same number of columns!");
+
+			for(i=0;i<M;i++){
+				dummy=0;
+				for(j=0;j<N;j++){
+					dummy+= this->matrix[N*i+j]*X->vector[j];
+				}
+				AX->vector[i]=dummy;
+			}
+
+		}
+		/*}}}*/
+		/*Duplicate{{{*/
+		IssmDenseMat<doubletype>* Duplicate(void){
+
+			doubletype dummy=0;
+
+			return new IssmDenseMat<doubletype>(this->matrix,this->M,this->N,dummy);
+
+		}
+		/*}}}*/
+		/*ToSerial{{{*/
+		doubletype* ToSerial(void){
+
+			doubletype* buffer=NULL;
+
+			if(this->M*this->N){
+				buffer=xNew<doubletype>(this->M*this->N);
+				xMemCpy<doubletype>(buffer,this->matrix,this->M*this->N);
+			}
+			return buffer;
+
+		}
+		/*}}}*/
+		/*SetValues{{{*/
+		void SetValues(int m,int* idxm,int n,int* idxn,doubletype* values,InsMode mode){
+
+			int i,j;
+			switch(mode){
+				case ADD_VAL:
+					for(i=0;i<m;i++) for(j=0;j<n;j++) this->matrix[N*idxm[i]+idxn[j]]+=values[n*i+j];
+					break;
+				case INS_VAL:
+					for(i=0;i<m;i++) for(j=0;j<n;j++) this->matrix[N*idxm[i]+idxn[j]]=values[n*i+j];
+					break;
+				default:
+					_error_("unknown insert mode!");
+					break;
+			}
+
+		}
+		/*}}}*/
+		/*Convert{{{*/
+		void Convert(MatrixType type){
+
+			/*do nothing*/
+
+		}
+		/*}}}*/		
+		#ifndef _HAVE_WRAPPERS_
+		/*Solve{{{*/
+		IssmAbsVec<IssmDouble>* Solve(IssmAbsVec<IssmDouble>* pfin, Parameters* parameters){
+
+			/*First off, we assume that the type of IssmAbsVec is IssmSeqVec. So downcast: */
+			IssmSeqVec<IssmDouble>* pf = NULL;
+			IssmSeqVec<IssmDouble> *uf = NULL;
+			IssmDouble* x=NULL;
+
+			/*Assume we are getting an IssmMpiVec in input, downcast: */
+			pf=(IssmSeqVec<IssmDouble>*)pfin;
+
+			#ifdef _HAVE_GSL_
+			DenseGslSolve(/*output*/ &x,/*stiffness matrix:*/ this->matrix,this->M,this->N, /*right hand side load vector: */ pf->vector,pf->M,parameters);
+
+			uf=new IssmSeqVec<IssmDouble>(x,this->N); xDelete(x);
+			return uf;
+			#else
+				_error_("GSL support not compiled in!");
+			#endif
+
+		}/*}}}*/
+		#endif
+};
+
+#endif //#ifndef _ISSM_DENSE_MAT_H_
Index: /issm/trunk/src/c/toolkits/issm/IssmMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMat.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmMat.h	(revision 15396)
@@ -0,0 +1,213 @@
+/*!\file:  IssmMat.h
+ * \brief Main Matrix class for the Issm toolkit. 
+ */ 
+
+#ifndef _ISSM_MAT_H_
+#define _ISSM_MAT_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include "../ToolkitOptions.h"
+#include "./IssmToolkitUtils.h"
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create Matrices that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  Such matrices 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)
+*/
+template <class doubletype> class IssmVec;
+template <class doubletype> class IssmDenseMat;
+template <class doubletype> class IssmMpiDenseMat;
+class Parameters;
+
+template <class doubletype> 
+class IssmMat{
+
+	public:
+
+		IssmAbsMat<doubletype>* matrix; /*abstract matrix, which implements object orientation*/
+
+		/*IssmMat constructors, destructors*/
+		IssmMat(){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>();
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>();
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmMat(int M,int N){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>(M,N);
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>(M,N);
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmMat(int M,int N, doubletype sparsity){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>(M,N,sparsity);
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>(M,N,sparsity);
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmMat(doubletype* serial_mat,int M,int N,doubletype sparsity){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>(serial_mat,M,N,sparsity);
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>(serial_mat,M,N,sparsity);
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+
+		}
+		/*}}}*/
+		IssmMat(int M,int N, int connectivity, int numberofdofspernode){ /*{{{*/
+
+			switch(IssmMatTypeFromToolkitOptions()){
+
+				case DenseEnum: 
+					this->matrix=new IssmDenseMat<doubletype>(M,N,connectivity,numberofdofspernode);
+					break;
+				case MpiDenseEnum:
+					#ifdef _HAVE_MPI_
+					this->matrix=new IssmMpiDenseMat<doubletype>(M,N,connectivity,numberofdofspernode);
+					#else
+					_error_("MpiDense matrix requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("matrix type not supported yet!");
+			}
+		}
+		/*}}}*/
+		~IssmMat(){ /*{{{*/
+			delete matrix;
+		} /*}}}*/
+
+		/*Functionality: */
+		void Echo(void){  /*{{{*/
+			matrix->Echo();
+		} /*}}}*/
+		void Assemble(void){  /*{{{*/
+			matrix->Assemble();
+		} /*}}}*/
+		doubletype Norm(NormMode mode){ /*{{{*/
+			return matrix->Norm(mode);
+		}
+		/*}}}*/
+		void GetSize(int* pM,int* pN){ /*{{{*/
+			matrix->GetSize(pM,pN);
+		} /*}}}*/
+		void GetLocalSize(int* pM,int* pN){ /*{{{*/
+			matrix->GetLocalSize(pM,pN);
+		} /*}}}*/
+		void MatMult(IssmVec<doubletype>* X,IssmVec<doubletype>* AX){ /*{{{*/
+			matrix->MatMult(X->vector,AX->vector);
+		} /*}}}*/
+		IssmMat<doubletype>* Duplicate(void){ /*{{{*/
+
+			IssmMat<doubletype>* issmmatrix=NULL;
+
+			issmmatrix=new IssmMat<doubletype>();
+			issmmatrix->matrix=this->matrix->Duplicate();
+
+			return issmmatrix;
+		} /*}}}*/
+		doubletype* ToSerial(void){/*{{{*/
+			return matrix->ToSerial();
+		}/*}}}*/
+		void SetValues(int m,int* idxm,int n,int* idxn,doubletype* values,InsMode mode){/*{{{*/
+			matrix->SetValues(m,idxm,n,idxn,values,mode);
+		}/*}}}*/
+		void Convert(MatrixType type){/*{{{*/
+			matrix->convert(type);
+		}/*}}}*/
+		#ifndef _HAVE_WRAPPERS_
+		IssmVec<doubletype>* Solve(IssmVec<doubletype>* pf, Parameters* parameters){ /*{{{*/
+
+			IssmVec<doubletype>* outvector=NULL;
+
+			outvector=new IssmVec<doubletype>();
+
+			outvector->vector=this->matrix->Solve(pf->vector,parameters);
+
+			return outvector;
+
+		}/*}}}*/
+		#endif
+};
+
+#endif //#ifndef _ISSMMAT_H_
Index: /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 15396)
@@ -0,0 +1,530 @@
+/*!\file:  IssmMpiDenseMat.h
+ * \brief implementation of parallel dense ISSM matrix. Internally, the parallel dense matrix is 
+ * split in rows across each cpu. Each matrix (representing a subset of rows) on each cpu is fully 
+ * dense, and is represented by a linear buffer of type doubletype. 
+ * This object needs to answer the API defined by the virtual functions in IssmAbsMat, 
+ * and the contructors required by IssmMat (see IssmMat.h)
+ */ 
+
+#ifndef _ISSM_MPI_DENSE_MAT_H_
+#define _ISSM_MPI_DENSE_MAT_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include "../../datastructures/datastructures.h"
+#include "../mumps/mumpsincludes.h"
+#include "./Bucket.h"
+#include "./IssmMpiVec.h"
+#include <math.h>
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create Matrices that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  Such matrices would be useful for use without or with the matlab or python
+  interface (which do not care for IssmDouble types, but only rely on
+  IssmPDouble types)*/
+template <class doubletype> class IssmAbsMat;
+
+template <class doubletype> 
+class IssmMpiDenseMat:public IssmAbsMat<doubletype>{
+
+	public:
+
+		int M,N;  //global size
+		int m;    //local number of rows
+		doubletype* matrix;  /*here, doubletype is either IssmDouble or IssmPDouble*/
+		DataSet*    buckets;  /*here, we store buckets of values that we will Assemble into a global matrix.*/
+
+		/*IssmMpiDenseMat constructors, destructors*/
+		/*FUNCTION IssmMpiDenseMat(){{{*/
+		IssmMpiDenseMat(){
+			this->M=0;
+			this->N=0;
+			this->m=0;
+			this->matrix=NULL;
+			this->buckets=new DataSet();
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiDenseMat(int M,int N){{{*/
+		IssmMpiDenseMat(int Min,int Nin){
+			this->Init(Min,Nin);
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiDenseMat(int M,int N, doubletype sparsity){{{*/
+		IssmMpiDenseMat(int pM,int pN, doubletype sparsity){
+			/*no sparsity involved here, we are fully dense, so just use the previous constructor: */
+			this->Init(pM,pN);
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiDenseMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
+		IssmMpiDenseMat(int min,int nin,int Min,int Nin,int* d_nnz,int* o_nnz){
+			/*not needed, we are fully dense!: */
+
+			this->buckets=new DataSet();
+
+			this->M=Min;
+			this->N=Nin;
+			this->m=min;
+
+			/*Initialize pointer: */
+			this->matrix=NULL;
+
+			/*Allocate: */
+			if (m*N)this->matrix=xNewZeroInit<doubletype>(this->m*N);
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiDenseMat(doubletype* serial_mat,int M,int N,doubletype sparsity){{{*/
+		IssmMpiDenseMat(doubletype* serial_mat,int Min,int Nin,doubletype sparsity){
+
+			/*Here, we assume that the serial_mat is local to the local cpu, and that it has 
+			 * the correct size (m rows by N colums), n determined by DetermineLocalSize: */
+			this->buckets=new DataSet();
+			this->M=Min;
+			this->N=Nin;
+			this->m=DetermineLocalSize(this->M,IssmComm::GetComm());
+
+			this->matrix=NULL;
+			if(m*N){
+				this->matrix=xNewZeroInit<doubletype>(m*N);
+				xMemCpy<doubletype>(this->matrix,serial_mat,m*N);
+			}
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiDenseMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
+		IssmMpiDenseMat(int pM,int pN, int connectivity,int numberofdofspernode){
+			/*not needed, we are fully dense!: */
+			this->Init(pM,pN);
+		}
+		/*}}}*/
+		/*FUNCTION ~IssmMpiDenseMat(){{{*/
+		~IssmMpiDenseMat(){
+			xDelete<doubletype>(this->matrix);
+			M=0;
+			N=0;
+			m=0;
+			delete this->buckets;
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiDenseMat::Init(int Min,int Nin){{{*/
+		void Init(int Min,int Nin){
+
+			this->buckets=new DataSet();
+
+			this->M=Min;
+			this->N=Nin;
+
+			/*Figure out local number of rows: */
+			this->m=DetermineLocalSize(this->M,IssmComm::GetComm());
+
+			/*Initialize pointer: */
+			this->matrix=NULL;
+
+			/*Allocate: */
+			if (m*N)this->matrix=xNewZeroInit<doubletype>(this->m*N);
+		}
+		/*}}}*/
+
+		/*IssmMpiDenseMat specific routines */
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+
+			int my_rank;
+			int i,j,k;
+
+			/*Do a synchronized dump across all the rows: */
+			my_rank=IssmComm::GetRank();
+			for(i=0;i<IssmComm::GetSize();i++){
+				if (my_rank==i){
+					_printf_("cpu " << i << " #rows: " << this->m << "\n");
+					for (j=0;j<this->m;j++){
+						_printf_("row " << j << "\n");
+						for (k=0;k<this->N;k++){
+							_printf_(this->matrix[j*this->N+k] << " \n");
+						}
+						_printf_("\n");
+					}
+				}
+				MPI_Barrier(IssmComm::GetComm());
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION Assemble{{{*/
+		void Assemble(){
+
+			int           i,j;
+
+			int         *RowRank            = NULL;
+			int           num_procs;
+
+			int        *row_indices_forcpu = NULL;
+			int        *col_indices_forcpu = NULL;
+			int        *modes_forcpu       = NULL;
+			doubletype *values_forcpu      = NULL;
+			int         *numvalues_forcpu   = NULL;
+			DataSet     **bucketsforcpu       = NULL;
+
+			int        **row_indices_fromcpu = NULL;
+			int        **col_indices_fromcpu = NULL;
+			int        **modes_fromcpu       = NULL;
+			doubletype **values_fromcpu      = NULL;
+			int         *numvalues_fromcpu   = NULL;
+
+			int           lower_row;
+			int           upper_row;
+			int*          sendcnts            = NULL;
+			int*          displs              = NULL;
+			int           count               = 0;
+
+			/*some communicator info: */
+			num_procs=IssmComm::GetSize();
+			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: */
+			RowRank=DetermineRowRankFromLocalSize(M,m,comm);
+
+			/*Now, sort out our dataset of buckets according to cpu ownership of rows: {{{*/
+			bucketsforcpu=xNew<DataSet*>(num_procs);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* bucketsofcpu_i=new DataSet();
+				for (j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket=(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->SpawnBucketsPerCpu(bucketsofcpu_i,i,RowRank);
+				}
+				bucketsforcpu[i]=bucketsofcpu_i;
+			}
+			/*}}}*/
+
+			/*Recap, each cpu has num_procs datasets of buckets. For a certain cpu j, for a given dataset i, the buckets this  {{{
+			 * dataset owns correspond to rows that are owned by cpu i, not j!. Out of all the buckets we own, make row,col,value,insert_mode 
+			 * vectors that will be shipped around the cluster: */
+			this->BucketsBuildScatterBuffers(&numvalues_forcpu,&row_indices_forcpu,&col_indices_forcpu,&values_forcpu,&modes_forcpu,bucketsforcpu,num_procs);
+			/*}}}*/
+
+			/*Now, we need to allocate on each cpu arrays to receive data from all the other cpus. To know what we need to allocate, we need  {{{
+			 *some scatter calls: */
+			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);
+			}
+
+			row_indices_fromcpu=xNew<int*>(num_procs);
+			col_indices_fromcpu=xNew<int*>(num_procs);
+			values_fromcpu=xNew<doubletype*>(num_procs);
+			modes_fromcpu=xNew<int*>(num_procs);
+			for(i=0;i<num_procs;i++){
+				int size=numvalues_fromcpu[i];
+				if(size){
+					row_indices_fromcpu[i]=xNew<int>(size);
+					col_indices_fromcpu[i]=xNew<int>(size);
+					values_fromcpu[i]=xNew<doubletype>(size);
+					modes_fromcpu[i]=xNew<int>(size);
+				}
+				else{
+					row_indices_fromcpu[i]=NULL;
+					col_indices_fromcpu[i]=NULL;
+					values_fromcpu[i]=NULL;
+					modes_fromcpu[i]=NULL;
+				}
+			}
+			/*}}}*/
+
+			/*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) :*/
+			sendcnts=xNew<int>(num_procs);
+			displs=xNew<int>(num_procs);
+			count=0;
+			for(i=0;i<num_procs;i++){
+				sendcnts[i]=numvalues_forcpu[i];
+				displs[i]=count;
+				count+=numvalues_forcpu[i];
+			}
+
+			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);
+			}
+			/*}}}*/
+
+			/*Plug values into global matrix: {{{*/
+			GetOwnershipBoundariesFromRange(&lower_row,&upper_row,m,comm);
+			for(i=0;i<num_procs;i++){
+				int  numvalues=numvalues_fromcpu[i];
+				int* rows=row_indices_fromcpu[i];
+				int* cols=col_indices_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+				int* mods=modes_fromcpu[i];
+
+				for(j=0;j<numvalues;j++){
+					if(mods[j]==ADD_VAL) *(matrix+N*(rows[j]-lower_row)+cols[j])+=values[j];
+					else *(matrix+N*(rows[j]-lower_row)+cols[j])=values[j];
+				}
+			}
+			/*}}}*/
+
+			/*Free ressources:{{{*/
+			xDelete<int>(RowRank);
+			xDelete<int>(row_indices_forcpu);
+			xDelete<int>(col_indices_forcpu);
+			xDelete<int>(modes_forcpu);
+			xDelete<doubletype>(values_forcpu);
+			xDelete<int>(numvalues_forcpu);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* buckets=bucketsforcpu[i];
+				delete buckets;
+			}
+			xDelete<DataSet*>(bucketsforcpu);
+
+			for(i=0;i<num_procs;i++){
+				int* rows=row_indices_fromcpu[i];
+				int* cols=col_indices_fromcpu[i];
+				int* modes=modes_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+
+				xDelete<int>(rows);
+				xDelete<int>(cols);
+				xDelete<int>(modes);
+				xDelete<doubletype>(values);
+			}
+			xDelete<int*>(row_indices_fromcpu);
+			xDelete<int*>(col_indices_fromcpu);
+			xDelete<int*>(modes_fromcpu);
+			xDelete<doubletype*>(values_fromcpu);
+			xDelete<int>(numvalues_fromcpu);
+
+			xDelete<int>(sendcnts);
+			xDelete<int>(displs);
+			/*}}}*/
+
+		}
+		/*}}}*/
+		/*FUNCTION Norm{{{*/
+		doubletype Norm(NormMode mode){
+
+			doubletype norm,local_norm;
+			doubletype absolute;
+			int i,j;
+
+			switch(mode){
+				case NORM_INF:
+					local_norm=0;
+					for(i=0;i<this->m;i++){
+						absolute=0;
+						for(j=0;j<this->N;j++){
+							absolute+=fabs(this->matrix[N*i+j]);
+						}
+						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());
+					return norm;
+					break; 
+				case NORM_FROB:
+					local_norm=0;
+					for(i=0;i<this->m;i++){
+						for(j=0;j<this->N;j++){
+							local_norm+=pow(this->matrix[N*i+j],2);
+						}
+					}
+					MPI_Reduce(&local_norm, &norm, 1, MPI_DOUBLE, MPI_SUM, 0, IssmComm::GetComm());
+					MPI_Bcast(&norm,1,MPI_DOUBLE,0,IssmComm::GetComm());
+					return sqrt(norm);
+					break; 
+
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		/*FUNCTION GetSize{{{*/
+		void GetSize(int* pM,int* pN){
+			*pM=M;
+			*pN=N;
+		}
+		/*}}}*/
+		/*FUNCTION GetLocalSize{{{*/
+		void GetLocalSize(int* pM,int* pN){
+			*pM=m;
+			*pN=N;
+		}
+		/*}}}*/
+		/*FUNCTION MatMult{{{*/
+		void MatMult(IssmAbsVec<doubletype>* Xin,IssmAbsVec<doubletype>* AXin){
+
+			int         i,j;
+			doubletype *X_serial  = NULL;
+
+			/*A check on the types: */
+			if(IssmVecTypeFromToolkitOptions()!=MpiEnum)_error_("MatMult operation only possible with 'mpi' vectors");
+
+			/*Now that we are sure, cast vectors: */
+			IssmMpiVec<doubletype>* X=(IssmMpiVec<doubletype>*)Xin;
+			IssmMpiVec<doubletype>* AX=(IssmMpiVec<doubletype>*)AXin;
+
+			/*Serialize input Xin: */
+			X_serial=X->ToMPISerial();
+
+			/*Every cpu has a serial version of the input vector. Use it to do the Matrix-Vector multiply 
+			 *locally and plug it into AXin: */
+			for(i=0;i<this->m;i++){
+				for(j=0;j<this->N;j++){
+					AX->vector[i]+=this->matrix[i*N+j]*X_serial[j];
+				}
+			}
+
+			/*Free ressources: */
+			xDelete<doubletype>(X_serial);
+		}
+		/*}}}*/
+		/*FUNCTION Duplicate{{{*/
+		IssmMpiDenseMat<doubletype>* Duplicate(void){
+
+			IssmMpiDenseMat<doubletype>* dup=new IssmMpiDenseMat<doubletype>(this->matrix,this->M,this->N,0);
+			return dup;
+
+		}
+		/*}}}*/
+		/*FUNCTION ToSerial{{{*/
+		doubletype* ToSerial(void){
+			_error_("not supported yet!");
+		}
+		/*}}}*/
+		/*FUNCTION SetValues{{{*/
+		void SetValues(int min,int* idxm,int nin,int* idxn,doubletype* values,InsMode mode){
+
+			/*we need to store all the values we collect here in order to Assemble later. 
+			 * Indeed, the values we are collecting here most of the time will not belong 
+			 * to us, but to another part of the matrix on another cpu: */
+			_assert_(buckets);
+
+			buckets->AddObject(new Bucket<doubletype>(min,idxm,nin,idxn,values,mode));
+
+		}
+		/*}}}*/
+		/*FUNCTION Convert{{{*/
+		void Convert(MatrixType type){
+			_error_("not supported yet!");
+		}
+		/*}}}*/		
+		/*FUNCTION BucketsBuildScatterBuffers{{{*/
+		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,int** pcol_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){
+
+			/*intermediary: */
+			int         i,j;
+			int         count                   = 0;
+			int         total_size              = 0;
+			int        *temp_row_indices_forcpu = NULL;
+			int        *temp_col_indices_forcpu = NULL;
+			doubletype *temp_values_forcpu      = NULL;
+			int        *temp_modes_forcpu       = NULL;
+
+			/*output: */
+			int        *numvalues_forcpu        = NULL;
+			int        *row_indices_forcpu      = NULL;
+			int        *col_indices_forcpu      = NULL;
+			doubletype *values_forcpu           = NULL;
+			int        *modes_forcpu            = NULL;
+
+			/*figure out size of buffers per cpu: */
+
+			numvalues_forcpu=xNew<int>(num_procs);
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+
+				count=0;
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					count+=bucket->MarshallSize();
+				}
+
+				numvalues_forcpu[i]=count;
+			}
+
+			/*now, figure out size of  total buffers (for all cpus!): */
+			count=0;
+			for(i=0;i<num_procs;i++){
+				count+=numvalues_forcpu[i];
+			}
+			total_size=count;
+
+			/*Allocate buffers: */
+			row_indices_forcpu = xNew<int>(total_size);
+			col_indices_forcpu = xNew<int>(total_size);
+			values_forcpu = xNew<doubletype>(total_size);
+			modes_forcpu = xNew<int>(total_size);
+
+			/*we are going to march through the buffers, and marshall data onto them, so in order to not
+			 *lose track of where these buffers are located in memory, we are going to work using copies 
+			 of them: */
+			temp_row_indices_forcpu=row_indices_forcpu;
+			temp_col_indices_forcpu=col_indices_forcpu;
+			temp_values_forcpu=values_forcpu;
+			temp_modes_forcpu=modes_forcpu;
+
+			/*Fill buffers: */
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->Marshall(&temp_row_indices_forcpu,&temp_col_indices_forcpu,&temp_values_forcpu,&temp_modes_forcpu); //pass in the address of the buffers, so as to have the Marshall routine increment them.
+				}
+			}
+
+			/*sanity check: */
+			if (temp_row_indices_forcpu!=row_indices_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_col_indices_forcpu!=col_indices_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_values_forcpu!=values_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_modes_forcpu!=modes_forcpu+total_size)_error_("problem with marshalling of buckets");
+
+			/*output buffers: */
+			*pnumvalues_forcpu   = numvalues_forcpu;
+			*prow_indices_forcpu = row_indices_forcpu;
+			*pcol_indices_forcpu = col_indices_forcpu;
+			*pvalues_forcpu      = values_forcpu;
+			*pmodes_forcpu       = modes_forcpu;
+		}
+		/*}}}*/		
+		#ifndef _HAVE_WRAPPERS_
+		/*Solve{{{*/
+		IssmAbsVec<IssmDouble>* Solve(IssmAbsVec<IssmDouble>* pfin, Parameters* parameters){
+
+			int i;
+
+			/*output: */
+			IssmMpiVec<IssmDouble>* uf=NULL;
+			IssmMpiVec<IssmDouble>* pf=NULL;
+
+			/*Assume we are getting an IssmMpiVec in input, downcast: */
+			pf=(IssmMpiVec<IssmDouble>*)pfin;
+
+			/*Initialize output: */
+			uf=pf->Duplicate();
+
+			/*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);
+			#else
+			_error_("IssmMpiDenseMat solver requires MUMPS solver");
+			#endif
+			return (IssmAbsVec<IssmDouble>*)uf;
+
+		}/*}}}*/
+		#endif
+};
+
+#endif //#ifndef _ISSM_MPI_DENSE_MAT_H_
Index: /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 15396)
@@ -0,0 +1,584 @@
+/*!\file:  IssmMpiVec.h
+ * \brief implementation of parallel dense ISSM vector. Internally, the parallel dense vector is 
+ * split in rows across each cpu. Each vector (representing a subset of rows) on each cpu is fully 
+ * dense, and is represented by a linear buffer of type doubletype. 
+ * This object needs to answer the API defined by the virtual functions in IssmAbsVec, 
+ * and the contructors required by IssmVec (see IssmVec.h)
+ */ 
+
+#ifndef _ISSM_MPI_VEC_H_
+#define _ISSM_MPI_VEC_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/io/io.h"
+#ifdef _HAVE_MPI_
+#include "../mpi/mpiincludes.h"
+#endif
+#include <math.h>
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create vectors that hold IssmDouble* vector or IssmPDouble* vector. 
+  Such vectors would be useful for use without or with the matlab or python interface (which do not care for IssmDouble types, 
+  but only rely on IssmPDouble types)*/
+template <class doubletype> class IssmAbsVec;
+
+template <class doubletype> 
+class IssmMpiVec:public IssmAbsVec<doubletype>{
+
+	public:
+
+		int M; //global size
+		int m; //local number of rows
+		doubletype* vector;  /*here, doubletype is either IssmDouble or IssmPDouble*/
+		DataSet*    buckets;  /*here, we store buckets of values that we will Assemble into a global vector.*/
+
+		/*IssmMpiVec constructors, destructors*/
+		/*FUNCTION IssmMpiVec(){{{*/
+		IssmMpiVec(){
+
+			this->M=0;
+			this->m=0;
+			this->vector=NULL;
+			this->buckets=new DataSet();
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiVec(int M){{{*/
+		IssmMpiVec(int Min){
+			this->Init(Min,false);
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiVec(int m,int M){{{*/
+		IssmMpiVec(int min, int Min){
+			this->Init(min,true);
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiVec(int M,bool fromlocalsize){{{*/
+		IssmMpiVec(int Min, bool fromlocalsize){
+			this->Init(Min,fromlocalsize);
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiVec(doubletype* serial_vec,int M){{{*/
+		IssmMpiVec(doubletype* buffer,int Min){
+
+			this->Init(Min,false);
+
+			if(this->M){
+				this->vector=xNew<doubletype>(this->m);
+				xMemCpy<doubletype>(this->vector,buffer,this->m);
+			}
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiVec(doubletype* serial_vec,int M,int m){{{*/
+		IssmMpiVec(doubletype* buffer,int Min,int min){
+
+			this->vector=NULL;
+			this->buckets=new DataSet();
+			this->M=Min;
+			this->m=min;
+
+			if(this->m){
+				this->vector=xNew<doubletype>(this->m);
+				xMemCpy<doubletype>(this->vector,buffer,this->m);
+			}
+		}
+		/*}}}*/
+		/*FUNCTION IssmMpiVec::Init(int Min,bool fromlocalsize){{{*/
+		void Init(int Min,bool fromlocalsize){
+
+			this->buckets=new DataSet();
+
+			if(fromlocalsize){
+				this->m=Min;
+				this->M=DetermineGlobalSize(this->m,IssmComm::GetComm());
+			}
+			else{
+				this->M=Min;
+				this->m=DetermineLocalSize(this->M,IssmComm::GetComm());
+			}
+
+			/*Initialize pointer: */
+			this->vector=NULL;
+
+			/*Allocate: */
+			if (m)this->vector=xNewZeroInit<doubletype>(this->m);
+		}
+		/*}}}*/
+		/*FUNCTION ~IssmMpiVec(){{{*/
+		~IssmMpiVec(){
+			xDelete<doubletype>(this->vector);
+			this->M=0;
+			this->m=0;
+			delete buckets;
+		}
+		/*}}}*/
+
+		/*IssmMpiVec specific routines*/
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+
+			int i,j;
+
+			/*Do a synchronized dump across all the rows: */
+			for(i=0;i<IssmComm::GetSize();i++){
+				if (IssmComm::GetRank()==i){
+					_printf_("cpu " << i << " #rows: " << this->m << "\n");
+					for (j=0;j<this->m;j++){
+						_printf_("row " << j << " " << this->vector[j] << "\n");
+					}
+					_printf_("\n");
+				}
+				MPI_Barrier(IssmComm::GetComm());
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Assemble{{{*/
+		void Assemble(){
+
+			int           i,j;
+
+			int         *RowRank            = NULL;
+			int           num_procs;
+
+			int        *row_indices_forcpu = NULL;
+			int        *col_indices_forcpu = NULL;
+			int        *modes_forcpu       = NULL;
+			doubletype *values_forcpu      = NULL;
+			int         *numvalues_forcpu   = NULL;
+			DataSet     **bucketsforcpu       = NULL;
+
+			int        **row_indices_fromcpu = NULL;
+			int        **col_indices_fromcpu = NULL;
+			int        **modes_fromcpu       = NULL;
+			doubletype **values_fromcpu      = NULL;
+			int         *numvalues_fromcpu   = NULL;
+
+			int           lower_row;
+			int           upper_row;
+			int*          sendcnts            = NULL;
+			int*          displs              = NULL;
+			int           count               = 0;
+
+			/*some communicator info: */
+			num_procs=IssmComm::GetSize();
+			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: */
+			RowRank=DetermineRowRankFromLocalSize(M,m,comm);
+
+			/*Now, sort out our dataset of buckets according to cpu ownership of rows: {{{*/
+			bucketsforcpu=xNew<DataSet*>(num_procs);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* bucketsofcpu_i=new DataSet();
+				for (j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket=(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->SpawnBucketsPerCpu(bucketsofcpu_i,i,RowRank);
+				}
+				bucketsforcpu[i]=bucketsofcpu_i;
+			}
+			/*}}}*/
+
+			/*Recap, each cpu has num_procs datasets of buckets. For a certain cpu j, for a given dataset i, the buckets this  {{{
+			 * dataset owns correspond to rows that are owned by cpu i, not j!. Out of all the buckets we own, make row,col,value,insert_mode 
+			 * vectors that will be shipped around the cluster: */
+			this->BucketsBuildScatterBuffers(&numvalues_forcpu,&row_indices_forcpu,&values_forcpu,&modes_forcpu,bucketsforcpu,num_procs);
+			/*}}}*/
+
+			/*Now, we need to allocate on each cpu arrays to receive data from all the other cpus. To know what we need to allocate, we need  {{{
+			 *some scatter calls: */
+			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);
+			}
+
+			row_indices_fromcpu=xNew<int*>(num_procs);
+			values_fromcpu=xNew<doubletype*>(num_procs);
+			modes_fromcpu=xNew<int*>(num_procs);
+			for(i=0;i<num_procs;i++){
+				int size=numvalues_fromcpu[i];
+				if(size){
+					row_indices_fromcpu[i]=xNew<int>(size);
+					values_fromcpu[i]=xNew<doubletype>(size);
+					modes_fromcpu[i]=xNew<int>(size);
+				}
+				else{
+					row_indices_fromcpu[i]=NULL;
+					values_fromcpu[i]=NULL;
+					modes_fromcpu[i]=NULL;
+				}
+			}
+			/*}}}*/
+
+			/*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) :*/
+			sendcnts=xNew<int>(num_procs);
+			displs=xNew<int>(num_procs);
+			count=0;
+			for(i=0;i<num_procs;i++){
+				sendcnts[i]=numvalues_forcpu[i];
+				displs[i]=count;
+				count+=numvalues_forcpu[i];
+			}
+
+			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);
+			}
+			/*}}}*/
+
+			/*Plug values into global vector: {{{*/
+			GetOwnershipBoundariesFromRange(&lower_row,&upper_row,m,comm);
+			for(i=0;i<num_procs;i++){
+				int  numvalues=numvalues_fromcpu[i];
+				int* rows=row_indices_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+				int* mods=modes_fromcpu[i];
+
+				for(j=0;j<numvalues;j++){
+					if(mods[j]==ADD_VAL) *(vector+(rows[j]-lower_row))+=values[j];
+					else *(vector+(rows[j]-lower_row))=values[j];
+				}
+			}
+			/*}}}*/
+
+			/*Free ressources:{{{*/
+			xDelete<int>(RowRank);
+			xDelete<int>(row_indices_forcpu);
+			xDelete<int>(modes_forcpu);
+			xDelete<doubletype>(values_forcpu);
+			xDelete<int>(numvalues_forcpu);
+
+			for(i=0;i<num_procs;i++){
+				DataSet* buckets=bucketsforcpu[i];
+				delete buckets;
+			}
+			xDelete<DataSet*>(bucketsforcpu);
+
+			for(i=0;i<num_procs;i++){
+				int* rows=row_indices_fromcpu[i];
+				int* modes=modes_fromcpu[i];
+				doubletype* values=values_fromcpu[i];
+
+				xDelete<int>(rows);
+				xDelete<int>(modes);
+				xDelete<doubletype>(values);
+			}
+			xDelete<int*>(row_indices_fromcpu);
+			xDelete<int*>(modes_fromcpu);
+			xDelete<doubletype*>(values_fromcpu);
+			xDelete<int>(numvalues_fromcpu);
+
+			xDelete<int>(sendcnts);
+			xDelete<int>(displs);
+			/*}}}*/
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValues{{{*/
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){
+
+			/*we need to store all the values we collect here in order to Assemble later. 
+			 * Indeed, the values we are collecting here most of the time will not belong 
+			 * to us, but to another part of the vector on another cpu: */
+			_assert_(buckets);
+
+			buckets->AddObject(new Bucket<doubletype>(ssize, list, values, mode));
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValue{{{*/
+		void SetValue(int dof, doubletype value, InsMode mode){
+
+			/*we need to store the value we collect here in order to Assemble later. 
+			 * Indeed, the value we are collecting here most of the time will not belong 
+			 * to us, but to another part of the vector on another cpu: */
+			_assert_(buckets);
+
+			buckets->AddObject(new Bucket<doubletype>(1,&dof,&value, mode));
+		}
+		/*}}}*/
+		/*FUNCTION GetValue{{{*/
+		void GetValue(doubletype* pvalue,int dof){
+			_error_("Get value on a MpiVec vector not implemented yet!");
+		}
+		/*}}}*/
+		/*FUNCTION GetSize{{{*/
+		void GetSize(int* pM){
+
+			*pM=this->M;
+
+		}
+		/*}}}*/
+		/*FUNCTION GetLocalSize{{{*/
+		void GetLocalSize(int* pM){
+
+			*pM=this->m;
+
+		}
+		/*}}}*/
+		/*FUNCTION Duplicate{{{*/
+		IssmMpiVec<doubletype>* Duplicate(void){
+
+			return new IssmMpiVec<doubletype>(this->vector,this->M,this->m);
+
+		}
+		/*}}}*/
+		/*FUNCTION Set{{{*/
+		void Set(doubletype value){
+
+			int i;
+			for(i=0;i<this->m;i++)this->vector[i]=value;
+
+		}
+		/*}}}*/
+		/*FUNCTION AXPY{{{*/
+		void AXPY(IssmAbsVec<doubletype>* Xin, doubletype a){
+
+			int i;
+
+			/*Assume X is of the correct type, and downcast: */
+			IssmMpiVec* X=NULL;
+
+			X=(IssmMpiVec<doubletype>*)Xin;
+
+			/*y=a*x+y where this->vector is y*/
+			for(i=0;i<this->m;i++)this->vector[i]=a*X->vector[i]+this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION AYPX{{{*/
+		void AYPX(IssmAbsVec<doubletype>* Xin, doubletype a){
+			int i;
+
+			/*Assume X is of the correct type, and downcast: */
+			IssmMpiVec* X=NULL;
+
+			X=(IssmMpiVec<doubletype>*)Xin;
+
+			/*y=x+a*y where this->vector is y*/
+			for(i=0;i<this->m;i++)this->vector[i]=X->vector[i]+a*this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION ToMPISerial{{{*/
+		doubletype* ToMPISerial(void){
+
+			/*communicator info: */
+			MPI_Comm comm;
+			int num_procs;
+
+			/*MPI_Allgatherv info: */
+			int  lower_row,upper_row;
+			int* recvcounts=NULL;
+			int* displs=NULL;
+
+			/*output: */
+			doubletype* buffer=NULL;
+
+			/*initialize comm info: */
+			comm=IssmComm::GetComm();
+			num_procs=IssmComm::GetSize();
+
+			/*Allocate: */
+			buffer=xNew<doubletype>(M);
+			recvcounts=xNew<int>(num_procs);
+			displs=xNew<int>(num_procs);
+
+			/*recvcounts:*/
+			MPI_Allgather(&this->m,1,MPI_INT,recvcounts,1,MPI_INT,comm);
+
+			/*get lower_row: */
+			GetOwnershipBoundariesFromRange(&lower_row,&upper_row,this->m,comm);
+
+			/*displs: */
+			MPI_Allgather(&lower_row,1,MPI_INT,displs,1,MPI_INT,comm);
+
+			/*All gather:*/
+			MPI_Allgatherv(this->vector, this->m, MPI_DOUBLE, buffer, recvcounts, displs, MPI_DOUBLE,comm);
+
+			/*free ressources: */
+			xDelete<int>(recvcounts);
+			xDelete<int>(displs);
+
+			/*return: */
+			return buffer;
+
+		}
+		/*}}}*/
+		/*FUNCTION Copy{{{*/
+		void Copy(IssmAbsVec<doubletype>* toin){
+
+			int i;
+
+			/*Assume toin is of the correct type, and downcast: */
+			IssmMpiVec* to=NULL;
+
+			to=(IssmMpiVec<doubletype>*)toin;
+
+			to->M=this->M;
+			for(i=0;i<this->m;i++)to->vector[i]=this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION Norm{{{*/
+		doubletype Norm(NormMode mode){
+
+			doubletype local_norm;
+			doubletype norm;
+			int i;
+
+			switch(mode){
+				case NORM_INF:
+					//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());
+					return norm;
+					break;
+				case NORM_TWO:
+					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());
+					return sqrt(norm);
+					break;
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Scale{{{*/
+		void Scale(doubletype scale_factor){
+
+			int i;
+			for(i=0;i<this->M;i++)this->vector[i]=scale_factor*this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION Dot{{{*/
+		doubletype Dot(IssmAbsVec<doubletype>* inputin){
+
+			int i;
+			doubletype local_dot=0;
+			doubletype dot=0;
+
+			/*Assume inputin is of the correct type, and downcast: */
+			IssmMpiVec* input=NULL;
+
+			input=(IssmMpiVec<doubletype>*)inputin;
+
+			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
+
+			return dot;
+		}
+		/*}}}*/
+		/*FUNCTION PointwiseDivide{{{*/
+		void PointwiseDivide(IssmAbsVec<doubletype>* xin,IssmAbsVec<doubletype>* yin){
+
+			int i;
+
+			/*Assume xin and yin are of the correct type, and downcast: */
+			IssmMpiVec* x=NULL;
+			IssmMpiVec* y=NULL;
+
+			x=(IssmMpiVec<doubletype>*)xin;
+			y=(IssmMpiVec<doubletype>*)yin;
+
+			/*pointwise w=x/y where this->vector is w: */
+			for(i=0;i<this->m;i++)this->vector[i]=x->vector[i]/y->vector[i];
+		}
+		/*}}}*/
+		/*FUNCTION BucketsBuildScatterBuffers{{{*/
+		void BucketsBuildScatterBuffers(int** pnumvalues_forcpu,int** prow_indices_forcpu,doubletype** pvalues_forcpu,int** pmodes_forcpu,DataSet** bucketsforcpu,int num_procs){
+
+			/*intermediary: */
+			int         i,j;
+			int         count                   = 0;
+			int         total_size              = 0;
+			int        *temp_row_indices_forcpu = NULL;
+			doubletype *temp_values_forcpu      = NULL;
+			int        *temp_modes_forcpu       = NULL;
+
+			/*output: */
+			int        *numvalues_forcpu        = NULL;
+			int        *row_indices_forcpu      = NULL;
+			doubletype *values_forcpu           = NULL;
+			int        *modes_forcpu            = NULL;
+
+			/*figure out size of buffers per cpu: */
+
+			numvalues_forcpu=xNew<int>(num_procs);
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+
+				count=0;
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					count+=bucket->MarshallSize();
+				}
+
+				numvalues_forcpu[i]=count;
+			}
+
+			/*now, figure out size of  total buffers (for all cpus!): */
+			count=0;
+			for(i=0;i<num_procs;i++){
+				count+=numvalues_forcpu[i];
+			}
+			total_size=count;
+
+			/*Allocate buffers: */
+			row_indices_forcpu = xNew<int>(total_size);
+			values_forcpu = xNew<doubletype>(total_size);
+			modes_forcpu = xNew<int>(total_size);
+
+			/*we are going to march through the buffers, and marshall data onto them, so in order to not
+			 *lose track of where these buffers are located in memory, we are going to work using copies 
+			 of them: */
+			temp_row_indices_forcpu=row_indices_forcpu;
+			temp_values_forcpu=values_forcpu;
+			temp_modes_forcpu=modes_forcpu;
+
+			/*Fill buffers: */
+			for(i=0;i<num_procs;i++){
+				DataSet    *buckets            = bucketsforcpu[i];
+				for(j=0;j<buckets->Size();j++){
+					Bucket<doubletype>* bucket =(Bucket<doubletype>*)buckets->GetObjectByOffset(j);
+					bucket->Marshall(&temp_row_indices_forcpu,&temp_values_forcpu,&temp_modes_forcpu); //pass in the address of the buffers, so as to have the Marshall routine increment them.
+				}
+			}
+
+			/*sanity check: */
+			if (temp_row_indices_forcpu!=row_indices_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_values_forcpu!=values_forcpu+total_size)_error_("problem with marshalling of buckets");
+			if (temp_modes_forcpu!=modes_forcpu+total_size)_error_("problem with marshalling of buckets");
+
+			/*output buffers: */
+			*pnumvalues_forcpu   = numvalues_forcpu;
+			*prow_indices_forcpu = row_indices_forcpu;
+			*pvalues_forcpu      = values_forcpu;
+			*pmodes_forcpu       = modes_forcpu;
+		}
+		/*}}}*/		
+};
+#endif //#ifndef _ISSM_MPI_VEC_H_	
Index: /issm/trunk/src/c/toolkits/issm/IssmSeqVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmSeqVec.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmSeqVec.h	(revision 15396)
@@ -0,0 +1,298 @@
+/*!\file:  IssmSeqVec.h
+ * \brief implementation of an ISSM vector which run serially (1 cpu only), which is made of a fully dense 
+ * vector. Internally, this dense vector is just a linear buffer of type doubletype. 
+ * This object needs to answer the API defined by the virtual functions in IssmAbsVec, 
+ * and the contructors required by IssmVec (see IssmVec.h)
+ */ 
+
+#ifndef _ISSM_SEQ_VEC_H_
+#define _ISSM_SEQ_VEC_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include <math.h>
+
+/*}}}*/
+
+/*We need to template this class, in case we want to create vectors that hold IssmDouble* vector or IssmPDouble* vector. 
+  Such vectors would be useful for use without or with the matlab or python interface (which do not care for IssmDouble types, 
+  but only rely on IssmPDouble types)*/
+
+template <class doubletype> class IssmAbsVec;
+
+template <class doubletype> 
+class IssmSeqVec: public IssmAbsVec<doubletype>{
+
+	public:
+
+		doubletype* vector;
+		int M;
+
+		/*IssmSeqVec constructors, destructors*/
+		/*FUNCTION IssmSeqVec(){{{*/
+		IssmSeqVec(){
+
+			this->M=0;
+			this->vector=NULL;
+		}
+		/*}}}*/
+		/*FUNCTION IssmSeqVec(int M){{{*/
+		IssmSeqVec(int pM){
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
+		}
+		/*}}}*/
+		/*FUNCTION IssmSeqVec(int m,int M){{{*/
+		IssmSeqVec(int pm,int pM){
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
+		}
+		/*}}}*/
+		/*FUNCTION IssmSeqVec(int M,bool fromlocalsize){{{*/
+		IssmSeqVec(int pM,bool fromlocalsize){
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
+		}
+		/*}}}*/
+		/*FUNCTION IssmSeqVec(doubletype* serial_vec,int M){{{*/
+		IssmSeqVec(doubletype* buffer,int pM){
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M){
+				this->vector=xNew<doubletype>(pM);
+				xMemCpy<doubletype>(this->vector,buffer,pM);
+			}
+		}
+		/*}}}*/
+		/*FUNCTION ~IssmSeqVec(){{{*/
+		~IssmSeqVec(){
+			if(this->M)xDelete<doubletype>(this->vector);
+			M=0;
+		}
+		/*}}}*/
+
+		/*IssmSeqVec specific routines*/
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+
+			int i;
+			_printf_("IssmSeqVec size " << this->M << "\n");
+			for(i=0;i<M;i++){
+				_printf_(vector[i] << "\n ");
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Assemble{{{*/
+		void Assemble(void){
+
+			/*do nothing*/
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValues{{{*/
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){
+
+			int i;
+			switch(mode){
+				case ADD_VAL:
+					for(i=0;i<ssize;i++) this->vector[list[i]]+=values[i];
+					break;
+				case INS_VAL:
+					for(i=0;i<ssize;i++) this->vector[list[i]]=values[i];
+					break;
+				default:
+					_error_("unknown insert mode!");
+					break;
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValue{{{*/
+		void SetValue(int dof, doubletype value, InsMode mode){
+
+			switch(mode){
+				case ADD_VAL:
+					this->vector[dof]+=value;
+					break;
+				case INS_VAL:
+					this->vector[dof]=value;
+					break;
+				default:
+					_error_("unknown insert mode!");
+					break;
+			}
+		}
+		/*}}}*/
+		/*FUNCTION GetValue{{{*/
+		void GetValue(doubletype* pvalue,int dof){
+
+			*pvalue=this->vector[dof];
+
+		}
+		/*}}}*/
+		/*FUNCTION GetSize{{{*/
+		void GetSize(int* pM){
+
+			*pM=this->M;
+
+		}
+		/*}}}*/
+		/*FUNCTION GetLocalSize{{{*/
+		void GetLocalSize(int* pM){
+
+			*pM=this->M;
+
+		}
+		/*}}}*/
+		/*FUNCTION Duplicate{{{*/
+		IssmSeqVec<doubletype>* Duplicate(void){
+
+			return new IssmSeqVec<doubletype>(this->vector,this->M);
+
+		}
+		/*}}}*/
+		/*FUNCTION Set{{{*/
+		void Set(doubletype value){
+
+			int i;
+			for(i=0;i<this->M;i++)this->vector[i]=value;
+
+		}
+		/*}}}*/
+		/*FUNCTION AXPY{{{*/
+		void AXPY(IssmAbsVec<doubletype>* Xin, doubletype a){
+
+			int i;
+
+			/*Assume X is of the correct type, and downcast: */
+			IssmSeqVec* X=NULL;
+
+			X=(IssmSeqVec<doubletype>*)Xin;
+
+			/*y=a*x+y where this->vector is y*/
+			for(i=0;i<this->M;i++)this->vector[i]=a*X->vector[i]+this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION AYPX{{{*/
+		void AYPX(IssmAbsVec<doubletype>* Xin, doubletype a){
+
+			int i;
+
+			/*Assume X is of the correct type, and downcast: */
+			IssmSeqVec* X=NULL;
+
+			X=(IssmSeqVec<doubletype>*)Xin;
+
+			/*y=x+a*y where this->vector is y*/
+			for(i=0;i<this->M;i++)this->vector[i]=X->vector[i]+a*this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION ToMPISerial{{{*/
+		doubletype* ToMPISerial(void){
+
+			doubletype* buffer=NULL;
+
+			if(this->M){
+				buffer=xNew<doubletype>(this->M);
+				xMemCpy<doubletype>(buffer,this->vector,this->M);
+			}
+			return buffer;
+
+		}
+		/*}}}*/
+		/*FUNCTION Copy{{{*/
+		void Copy(IssmAbsVec<doubletype>* toin){
+
+			int i;
+
+			/*Assume toin is of the correct type, and downcast: */
+			IssmSeqVec* to=NULL;
+
+			to=(IssmSeqVec<doubletype>*)toin;
+
+			to->M=this->M;
+			for(i=0;i<this->M;i++)to->vector[i]=this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION Norm{{{*/
+		doubletype Norm(NormMode mode){
+
+			doubletype norm;
+			int i;
+
+			switch(mode){
+				case NORM_INF:
+					//norm=0; for(i=0;i<this->M;i++)norm=max(norm,fabs(this->vector[i]));
+					norm=0; for(i=0;i<this->M;i++)norm=max(norm,this->vector[i]);
+					return norm;
+					break;
+				case NORM_TWO:
+					norm=0; 
+					for(i=0;i<this->M;i++)norm+=pow(this->vector[i],2);
+					return sqrt(norm);
+					break;
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Scale{{{*/
+		void Scale(doubletype scale_factor){
+
+			int i;
+			for(i=0;i<this->M;i++)this->vector[i]=scale_factor*this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION Dot{{{*/
+		doubletype Dot(IssmAbsVec<doubletype>* inputin){
+
+			int i;
+
+			/*Assume inputin is of the correct type, and downcast: */
+			IssmSeqVec* input=NULL;
+
+			input=(IssmSeqVec<doubletype>*)inputin;
+
+			doubletype dot=0;
+			for(i=0;i<this->M;i++)dot+=this->vector[i]*input->vector[i];
+			return dot;
+
+		}
+		/*}}}*/
+		/*FUNCTION PointwiseDivide{{{*/
+		void PointwiseDivide(IssmAbsVec<doubletype>* xin,IssmAbsVec<doubletype>* yin){
+
+			int i;
+
+			/*Assume xin and yin are of the correct type, and downcast: */
+			IssmSeqVec* x=NULL;
+			IssmSeqVec* y=NULL;
+
+			x=(IssmSeqVec<doubletype>*)xin;
+			y=(IssmSeqVec<doubletype>*)yin;
+
+			/*pointwise w=x/y where this->vector is w: */
+			for(i=0;i<this->M;i++)this->vector[i]=x->vector[i]/y->vector[i];
+		}
+		/*}}}*/
+};
+#endif //#ifndef _ISSM_SEQ_VEC_H_
Index: /issm/trunk/src/c/toolkits/issm/IssmSolver.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmSolver.cpp	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmSolver.cpp	(revision 15396)
@@ -0,0 +1,24 @@
+/*!\file IssmSolver
+ * \brief implementation of solver 
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <cstring>
+
+#include "../../shared/shared.h"
+#include "./issmtoolkit.h"
+
+void IssmSolve(IssmVec<IssmDouble>** pout,IssmMat<IssmDouble>* Kff, IssmVec<IssmDouble>* pf, Parameters* parameters){/*{{{*/
+
+	/*Let matrix decide, to retain object orientation: */
+	IssmVec<IssmDouble>* outvector=NULL;
+
+	outvector=Kff->Solve(pf,parameters);
+
+	*pout=outvector;
+}
+/*}}}*/
Index: /issm/trunk/src/c/toolkits/issm/IssmSolver.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmSolver.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmSolver.h	(revision 15396)
@@ -0,0 +1,26 @@
+/*!\file:  IssmSolver.h
+ * \brief main hook up from Solver toolkit object to the ISSM toolkit
+ */ 
+
+#ifndef _ISSM_SOLVER_H_
+#define _ISSM_SOLVER_H_
+
+/*Headers:*/
+/*{{{*/
+#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"
+
+/*}}}*/
+
+template <class doubletype> class IssmVec;
+template <class doubletype> class IssmMat;
+class Parameters;
+
+void IssmSolve(IssmVec<IssmDouble>** puf,IssmMat<IssmDouble>* Kff, IssmVec<IssmDouble>* pf,Parameters* parameters);
+
+#endif 
Index: /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp	(revision 15396)
@@ -0,0 +1,76 @@
+/*!\file:  IssmToolkitUtils.cpp
+ * \brief utilities used throughout our ISSM toolkit
+ */ 
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/io/Comm/Comm.h"
+#include "../../shared/Enum/Enum.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../ToolkitOptions.h"
+#include "./IssmToolkitUtils.h"
+#include <string.h>
+/*}}}*/
+
+/*Routines: */
+int IssmMatTypeFromToolkitOptions(void){ /*{{{*/
+
+	char *mat_type      = NULL;
+	int   mat_type_enum;
+	int   num_procs     = 0;
+	bool  isparallel    = false;
+
+	/*first, figure out if we are running in parallel: */
+	num_procs=IssmComm::GetSize();
+	if(num_procs>1)isparallel=true;
+
+	/*retrieve matrix type as a string, from the Toolkits Options database, similar to what Petsc does. Actually, 
+	 *we try and stick with the Petsc matrix types: */
+	mat_type=ToolkitOptions::GetToolkitOptionValue("mat_type");
+
+	if ((strcmp(mat_type,"mpidense")==0) || (strcmp(mat_type,"dense")==0)){
+		if (isparallel) mat_type_enum=MpiDenseEnum;
+		else mat_type_enum=DenseEnum;
+	}
+	else _error_("matrix type not supported yet!");
+
+	/*free ressources: */
+	xDelete<char>(mat_type);
+
+	/*return: */
+	return mat_type_enum;
+} /*}}}*/
+int IssmVecTypeFromToolkitOptions(void){ /*{{{*/
+
+	char* vec_type=NULL;
+	int   vec_type_enum;
+	int   num_procs=0;
+	bool  isparallel=false;
+
+	/*first, figure out if we are running in parallel: */
+	num_procs=IssmComm::GetSize();
+	if(num_procs>1)isparallel=true;
+
+	/*retrieve vector type as a string, from the Toolkits Options database, similar to what Petsc does. Actually, 
+	 *we try and stick with the Petsc vector types: */
+	vec_type=ToolkitOptions::GetToolkitOptionValue("vec_type");
+
+	if ((strcmp(vec_type,"mpi")==0) || (strcmp(vec_type,"seq")==0)){
+		if (isparallel) vec_type_enum=MpiEnum;
+		else vec_type_enum=SeqEnum;
+	}
+	else _error_("vector type not supported yet!");
+
+	/*free ressources: */
+	xDelete<char>(vec_type);
+
+	/*return: */
+	return vec_type_enum;
+} /*}}}*/  
Index: /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.h	(revision 15396)
@@ -0,0 +1,21 @@
+/*!\file:  IssmToolkitUtils.h
+ * \brief routines used throughout the ISSM toolkit
+ */ 
+
+#ifndef _ISSM_TOOLKIT_UTILS_H_
+#define _ISSM_TOOLKIT_UTILS_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*}}}*/
+
+int IssmMatTypeFromToolkitOptions(void);
+int IssmVecTypeFromToolkitOptions(void);
+
+#endif //#ifndef _ISSMMAT_H_
Index: /issm/trunk/src/c/toolkits/issm/IssmVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmVec.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/issm/IssmVec.h	(revision 15396)
@@ -0,0 +1,204 @@
+/*!\file:  IssmVec.h
+ * \brief Main Vector class for the Issm toolkit. 
+ */ 
+
+#ifndef _ISSMVEC_H_
+#define _ISSMVEC_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Enum/Enum.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/MemOps.h"
+#include "./IssmToolkitUtils.h"
+#include <math.h>
+/*}}}*/
+
+/*We need to template this class, in case we want to create Vectors that hold
+  IssmDouble* matrix or IssmPDouble* matrix. 
+  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)
+*/
+int IssmVecTypeFromToolkitOptions(void);
+template <class doubletype> class IssmSeqVec;
+template <class doubletype> class IssmMpiVec;
+
+template <class doubletype> 
+class IssmVec{
+
+	public:
+
+		IssmAbsVec<doubletype>* vector; /*abstract vector, which implements object orientation*/
+
+		/*IssmVec constructors, destructors*/
+		IssmVec(){ /*{{{*/
+			this->vector=NULL;
+		}
+		/*}}}*/
+		IssmVec(int M){/*{{{*/
+
+			switch(IssmVecTypeFromToolkitOptions()){
+
+				case SeqEnum: 
+					this->vector=new IssmSeqVec<doubletype>(M);
+					break;
+				case MpiEnum:
+					#ifdef _HAVE_MPI_
+					this->vector=new IssmMpiVec<doubletype>(M);
+					#else
+					_error_("Mpi vector requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("vector type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmVec(int m,int M){/*{{{*/
+
+			switch(IssmVecTypeFromToolkitOptions()){
+
+				case SeqEnum: 
+					this->vector=new IssmSeqVec<doubletype>(m,M);
+					break;
+				case MpiEnum:
+					#ifdef _HAVE_MPI_
+					this->vector=new IssmMpiVec<doubletype>(m,M);
+					#else
+					_error_("Mpi vector requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("vector type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmVec(int M,bool fromlocalsize){/*{{{*/
+
+			switch(IssmVecTypeFromToolkitOptions()){
+
+				case SeqEnum: 
+					this->vector=new IssmSeqVec<doubletype>(M,fromlocalsize);
+					break;
+				case MpiEnum:
+					#ifdef _HAVE_MPI_
+					this->vector=new IssmMpiVec<doubletype>(M,fromlocalsize);
+					#else
+					_error_("Mpi vector requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("vector type not supported yet!");
+			}
+		}
+		/*}}}*/
+		IssmVec(doubletype* buffer,int M){/*{{{*/
+
+			switch(IssmVecTypeFromToolkitOptions()){
+
+				case SeqEnum: 
+					this->vector=new IssmSeqVec<doubletype>(buffer,M);
+					break;
+				case MpiEnum:
+					#ifdef _HAVE_MPI_
+					this->vector=new IssmMpiVec<doubletype>(buffer,M);
+					#else
+					_error_("Mpi vector requires compilation of MPI!");
+					#endif
+					break;
+				default:
+					_error_("vector type not supported yet!");
+			}
+		}
+		/*}}}*/
+		~IssmVec(){/*{{{*/
+			delete this->vector;
+		}
+		/*}}}*/
+
+		/*IssmVec specific routines*/
+		void Echo(void){/*{{{*/
+			vector->Echo();
+		}
+		/*}}}*/
+		void Assemble(void){/*{{{*/
+			vector->Assemble();
+		}
+		/*}}}*/
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){/*{{{*/
+			vector->SetValues(ssize,list,values,mode);
+		}
+		/*}}}*/
+		void SetValue(int dof, doubletype value, InsMode mode){/*{{{*/
+			vector->SetValue(dof,value,mode);
+		}
+		/*}}}*/
+		void GetValue(doubletype* pvalue,int dof){/*{{{*/
+			vector->GetValue(pvalue,dof);
+		}
+		/*}}}*/
+		void GetSize(int* pM){/*{{{*/
+			vector->GetSize(pM);
+		}
+		/*}}}*/
+		void GetLocalSize(int* pM){/*{{{*/
+			vector->GetLocalSize(pM);
+		}
+		/*}}}*/
+		IssmVec<doubletype>* Duplicate(void){/*{{{*/
+
+			IssmVec<doubletype>* issmvector=NULL;
+
+			issmvector=new IssmVec<doubletype>();
+			issmvector->vector=this->vector->Duplicate();
+			this->vector->Copy(issmvector->vector);
+
+			return issmvector;
+		}
+		/*}}}*/
+		void Set(doubletype value){/*{{{*/
+			vector->Set(value);
+		}
+		/*}}}*/
+		void AXPY(IssmVec* X, doubletype a){/*{{{*/
+			vector->AXPY(X->vector,a);
+		}
+		/*}}}*/
+		void AYPX(IssmVec* X, doubletype a){/*{{{*/
+			vector->AYPX(X->vector,a);
+		}
+		/*}}}*/
+		doubletype* ToMPISerial(void){/*{{{*/
+			return vector->ToMPISerial();
+		}
+		/*}}}*/
+		void Copy(IssmVec* to){/*{{{*/
+			vector->Copy(to->vector);
+		}
+		/*}}}*/
+		doubletype Norm(NormMode mode){/*{{{*/
+			return vector->Norm(mode);
+		}
+		/*}}}*/
+		void Scale(doubletype scale_factor){/*{{{*/
+			vector->Scale(scale_factor);
+		}
+		/*}}}*/
+		doubletype Dot(IssmVec* input){/*{{{*/
+			return vector->Dot(input->vector);
+		}
+		/*}}}*/
+		void PointwiseDivide(IssmVec* x,IssmVec* y){/*{{{*/
+			vector->PointwiseDivide(x->vector,y->vector);
+		}
+		/*}}}*/
+};
+
+#endif //#ifndef _ISSMVEC_H_
Index: sm/trunk/src/c/toolkits/issm/SeqMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/SeqMat.h	(revision 15395)
+++ 	(revision )
@@ -1,238 +1,0 @@
-/*!\file:  SeqMat.h
- * \brief wrapper to SeqMat objects, which are just wrappers to a simple IssmDouble or IssmPDouble* buffer.
- */ 
-
-#ifndef _SEQMAT_H_
-#define _SEQMAT_H_
-
-/*Headers:*/
-/*{{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "../../shared/Exceptions/exceptions.h"
-#include "../../shared/MemOps/xMemCpy.h"
-#include "../../shared/Alloc/alloc.h"
-#include "../../include/macros.h"
-#include "./SeqVec.h"
-
-/*}}}*/
-
-/*We need to template this class, in case we want to create Matrices that hold IssmDouble* matrix or IssmPDouble* matrix. 
-  Such matrices would be useful for use without or with the matlab or python interface (which do not care for IssmDouble types, 
-  but only rely on IssmPDouble types)*/
-
-template <class doubletype> 
-class SeqMat{
-
-	public:
-
-		int M,N; 
-		doubletype* matrix;  /*here, doubletype is either IssmDouble or IssmPDouble*/
-
-		/*SeqMat constructors, destructors*/
-		/*FUNCTION SeqMat(){{{*/
-		SeqMat(){
-
-			this->M=0;
-			this->N=0;
-			this->matrix=NULL;
-		}
-		/*}}}*/
-		/*FUNCTION SeqMat(int M,int N){{{*/
-		SeqMat(int pM,int pN){
-
-			this->M=pM;
-			this->N=pN;
-			this->matrix=NULL;
-			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
-		}
-		/*}}}*/
-		/*FUNCTION SeqMat(int M,int N, doubletype sparsity){{{*/
-		SeqMat(int pM,int pN, doubletype sparsity){
-
-			this->M=pM;
-			this->N=pN;
-			this->matrix=NULL;
-			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
-		}
-		/*}}}*/
-		/*FUNCTION SeqMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
-		SeqMat(int m,int n,int pM,int pN,int* d_nnz,int* o_nnz){
-
-			this->M=pM;
-			this->N=pN;
-			this->matrix=NULL;
-			if(pM*pN) this->matrix=xNewZeroInit<doubletype>(pM*pN);
-		}
-		/*}}}*/
-		/*FUNCTION SeqMat(doubletype* serial_mat,int M,int N,doubletype sparsity){{{*/
-		SeqMat(doubletype* serial_mat,int pM,int pN,doubletype sparsity){
-
-			this->M=pM;
-			this->N=pN;
-			this->matrix=NULL;
-			if(M*N){
-				this->matrix=xNewZeroInit<doubletype>(pM*pN);
-				xMemCpy<doubletype>(this->matrix,serial_mat,pM*pN);
-			}
-
-		}
-		/*}}}*/
-		/*FUNCTION SeqMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
-		SeqMat(int pM,int pN, int connectivity,int numberofdofspernode){
-
-			this->M=pM;
-			this->N=pN;
-			this->matrix=NULL;
-			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
-		}
-		/*}}}*/
-		/*FUNCTION ~SeqMat(){{{*/
-		~SeqMat(){
-
-			xDelete<doubletype>(this->matrix);
-			M=0;
-			N=0;
-		}
-		/*}}}*/
-
-		/*SeqMat specific routines */
-		/*FUNCTION Echo{{{*/
-		void Echo(void){
-
-			int i,j;
-			_printLine_("SeqMat size " << this->M << "-" << this->N);
-			for(i=0;i<M;i++){
-				for(j=0;j<N;j++){
-					_printString_(this->matrix[N*i+j] << " ");
-				}
-				_printLine_("");
-			}
-		}
-		/*}}}*/
-		/*FUNCTION Assemble{{{*/
-		void Assemble(void){
-
-			/*do nothing*/
-
-		}
-		/*}}}*/
-		/*FUNCTION Norm{{{*/
-		doubletype Norm(NormMode mode){
-
-			doubletype norm;
-			doubletype absolute;
-			int i,j;
-
-			switch(mode){
-				case NORM_INF:
-					norm=0;
-					for(i=0;i<this->M;i++){
-						absolute=0;
-						for(j=0;j<this->N;j++){
-							absolute+=fabs(this->matrix[N*i+j]);
-						}
-						norm=max(norm,absolute);
-					}
-					return norm;
-					break; 
-				default:
-					_error_("unknown norm !");
-					break;
-			}
-		}
-		/*}}}*/
-		/*FUNCTION GetSize{{{*/
-		void GetSize(int* pM,int* pN){
-
-			*pM=this->M;
-			*pN=this->N;
-
-		}
-		/*}}}*/
-		/*FUNCTION GetLocalSize{{{*/
-		void GetLocalSize(int* pM,int* pN){
-
-			*pM=this->M;
-			*pN=this->N;
-
-		}
-		/*}}}*/
-		/*FUNCTION MatMult{{{*/
-		void MatMult(SeqVec<doubletype>* X,SeqVec<doubletype>* AX){
-
-			int i,j;
-			int XM,AXM;
-			doubletype dummy;
-
-			X->GetSize(&XM);
-			AX->GetSize(&AXM);
-
-			if(M!=AXM)_error_("A and AX should have the same number of rows!");
-			if(N!=XM)_error_("A and X should have the same number of columns!");
-
-			for(i=0;i<M;i++){
-				dummy=0;
-				for(j=0;j<N;j++){
-					dummy+= this->matrix[N*i+j]*X->vector[j];
-				}
-				AX->vector[i]=dummy;
-			}
-
-		}
-		/*}}}*/
-		/*FUNCTION Duplicate{{{*/
-		SeqMat* Duplicate(void){
-
-			doubletype dummy=0;
-
-			return new SeqMat(this->matrix,this->M,this->N,dummy);
-
-		}
-		/*}}}*/
-		/*FUNCTION ToSerial{{{*/
-		doubletype* ToSerial(void){
-
-			doubletype* buffer=NULL;
-
-			if(this->M*this->N){
-				buffer=xNew<doubletype>(this->M*this->N);
-				xMemCpy<doubletype>(buffer,this->matrix,this->M*this->N);
-			}
-			return buffer;
-
-		}
-		/*}}}*/
-		/*FUNCTION SetValues{{{*/
-		void SetValues(int m,int* idxm,int n,int* idxn,doubletype* values,InsMode mode){
-
-			int i,j;
-			switch(mode){
-				case ADD_VAL:
-					for(i=0;i<m;i++) for(j=0;j<n;j++) this->matrix[N*idxm[i]+idxn[j]]+=values[n*i+j];
-					break;
-				case INS_VAL:
-					for(i=0;i<m;i++) for(j=0;j<n;j++) this->matrix[N*idxm[i]+idxn[j]]=values[n*i+j];
-					break;
-				default:
-					_error_("unknown insert mode!");
-					break;
-			}
-
-		}
-		/*}}}*/
-		/*FUNCTION Convert{{{*/
-		void Convert(MatrixType type){
-
-			/*do nothing*/
-
-		}
-		/*}}}*/		
-
-};
-
-#endif //#ifndef _SEQMAT_H_
Index: sm/trunk/src/c/toolkits/issm/SeqVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/SeqVec.h	(revision 15395)
+++ 	(revision )
@@ -1,266 +1,0 @@
-/*!\file:  SeqVec.h
- * \brief wrapper to our SeqVec object, which is just a wrapper to a IssmDouble* 
- */ 
-
-#ifndef _SEQVEC_H_
-#define _SEQVEC_H_
-
-/*Headers:*/
-/*{{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "../../shared/Exceptions/exceptions.h"
-#include "../../shared/MemOps/xMemCpy.h"
-#include "../../shared/Alloc/alloc.h"
-#include "../../include/macros.h"
-
-/*}}}*/
-
-/*We need to template this class, in case we want to create vectors that hold IssmDouble* matrix or IssmPDouble* matrix. 
-  Such vectors would be useful for use without or with the matlab or python interface (which do not care for IssmDouble types, 
-  but only rely on IssmPDouble types)*/
-
-template <class doubletype> 
-class SeqVec{
-
-	public:
-
-		doubletype* vector;
-		int M;
-
-		/*SeqVec constructors, destructors*/
-		/*FUNCTION SeqVec(){{{*/
-		SeqVec(){
-
-			this->M=0;
-			this->vector=NULL;
-		}
-		/*}}}*/
-		/*FUNCTION SeqVec(int M){{{*/
-		SeqVec(int pM){
-
-			this->M=pM;
-			this->vector=NULL;
-			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
-		}
-		/*}}}*/
-		/*FUNCTION SeqVec(int m,int M){{{*/
-		SeqVec(int pm,int pM){
-
-			this->M=pM;
-			this->vector=NULL;
-			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
-		}
-		/*}}}*/
-		/*FUNCTION SeqVec(int M,bool fromlocalsize){{{*/
-		SeqVec(int pM,bool fromlocalsize){
-
-			this->M=pM;
-			this->vector=NULL;
-			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
-		}
-		/*}}}*/
-		/*FUNCTION SeqVec(doubletype* serial_vec,int M){{{*/
-		SeqVec(doubletype* buffer,int pM){
-
-			this->M=pM;
-			this->vector=NULL;
-			if(this->M){
-				this->vector=xNew<doubletype>(pM);
-				xMemCpy<doubletype>(this->vector,buffer,pM);
-			}
-		}
-		/*}}}*/
-		/*FUNCTION ~SeqVec(){{{*/
-		~SeqVec(){
-			xDelete<doubletype>(this->vector);
-			M=0;
-		}
-		/*}}}*/
-
-		/*SeqVec specific routines*/
-		/*FUNCTION Echo{{{*/
-		void Echo(void){
-
-			int i;
-			_printLine_("SeqVec size " << this->M);
-			for(i=0;i<M;i++){
-				_printString_(vector[i] << "\n ");
-			}
-		}
-		/*}}}*/
-		/*FUNCTION Assemble{{{*/
-		void Assemble(void){
-
-			/*do nothing*/
-
-		}
-		/*}}}*/
-		/*FUNCTION SetValues{{{*/
-		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){
-
-			int i;
-			switch(mode){
-				case ADD_VAL:
-					for(i=0;i<ssize;i++) this->vector[list[i]]+=values[i];
-					break;
-				case INS_VAL:
-					for(i=0;i<ssize;i++) this->vector[list[i]]=values[i];
-					break;
-				default:
-					_error_("unknown insert mode!");
-					break;
-			}
-
-		}
-		/*}}}*/
-		/*FUNCTION SetValue{{{*/
-		void SetValue(int dof, doubletype value, InsMode mode){
-
-			switch(mode){
-				case ADD_VAL:
-					this->vector[dof]+=value;
-					break;
-				case INS_VAL:
-					this->vector[dof]=value;
-					break;
-				default:
-					_error_("unknown insert mode!");
-					break;
-			}
-		}
-		/*}}}*/
-		/*FUNCTION GetValue{{{*/
-		void GetValue(doubletype* pvalue,int dof){
-
-			*pvalue=this->vector[dof];
-
-		}
-		/*}}}*/
-		/*FUNCTION GetSize{{{*/
-		void GetSize(int* pM){
-
-			*pM=this->M;
-
-		}
-		/*}}}*/
-		/*FUNCTION GetLocalSize{{{*/
-		void GetLocalSize(int* pM){
-
-			*pM=this->M;
-
-		}
-		/*}}}*/
-		/*FUNCTION Duplicate{{{*/
-		SeqVec* Duplicate(void){
-
-			return new SeqVec(this->vector,this->M);
-
-		}
-		/*}}}*/
-		/*FUNCTION Set{{{*/
-		void Set(doubletype value){
-
-			int i;
-			for(i=0;i<this->M;i++)this->vector[i]=value;
-
-		}
-		/*}}}*/
-		/*FUNCTION AXPY{{{*/
-		void AXPY(SeqVec* X, doubletype a){
-
-			int i;
-
-			/*y=a*x+y where this->vector is y*/
-			for(i=0;i<this->M;i++)this->vector[i]=a*X->vector[i]+this->vector[i];
-
-		}
-		/*}}}*/
-		/*FUNCTION AYPX{{{*/
-		void AYPX(SeqVec* X, doubletype a){
-
-			int i;
-
-			/*y=x+a*y where this->vector is y*/
-			for(i=0;i<this->M;i++)this->vector[i]=X->vector[i]+a*this->vector[i];
-
-		}
-		/*}}}*/
-		/*FUNCTION ToMPISerial{{{*/
-		doubletype* ToMPISerial(void){
-
-			doubletype* buffer=NULL;
-
-			if(this->M){
-				buffer=xNew<doubletype>(this->M);
-				xMemCpy<doubletype>(buffer,this->vector,this->M);
-			}
-			return buffer;
-
-		}
-		/*}}}*/
-		/*FUNCTION Copy{{{*/
-		void Copy(SeqVec* to){
-
-			int i;
-
-			to->M=this->M;
-			for(i=0;i<this->M;i++)to->vector[i]=this->vector[i];
-
-		}
-		/*}}}*/
-		/*FUNCTION Norm{{{*/
-		doubletype Norm(NormMode mode){
-
-			doubletype norm;
-			int i;
-
-			switch(mode){
-				case NORM_INF:
-					norm=0; for(i=0;i<this->M;i++)norm=max(norm,fabs(this->vector[i]));
-					return norm;
-					break;
-				case NORM_TWO:
-					norm=0; 
-					for(i=0;i<this->M;i++)norm+=pow(this->vector[i],2);
-					return sqrt(norm);
-					break;
-				default:
-					_error_("unknown norm !");
-					break;
-			}
-		}
-		/*}}}*/
-		/*FUNCTION Scale{{{*/
-		void Scale(doubletype scale_factor){
-
-			int i;
-			for(i=0;i<this->M;i++)this->vector[i]=scale_factor*this->vector[i];
-
-		}
-		/*}}}*/
-		/*FUNCTION Dot{{{*/
-		doubletype Dot(SeqVec* input){
-
-			int i;
-
-			doubletype dot=0;
-			for(i=0;i<this->M;i++)dot+=this->vector[i]*input->vector[i];
-			return dot;
-
-		}
-		/*}}}*/
-		/*FUNCTION PointwiseDivide{{{*/
-		void PointwiseDivide(SeqVec* x,SeqVec* y){
-
-			int i;
-			/*pointwise w=x/y where this->vector is w: */
-			for(i=0;i<this->M;i++)this->vector[i]=x->vector[i]/y->vector[i];
-		}
-		/*}}}*/
-};
-#endif //#ifndef _SEQVEC_H_
Index: /issm/trunk/src/c/toolkits/issm/issmtoolkit.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/issmtoolkit.h	(revision 15395)
+++ /issm/trunk/src/c/toolkits/issm/issmtoolkit.h	(revision 15396)
@@ -6,6 +6,22 @@
 #define _ISSM_TOOLKIT_H_
 
-#include "./SeqMat.h"
-#include "./SeqVec.h"
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./IssmAbsMat.h"
+#include "./IssmAbsVec.h"
+#include "./IssmDenseMat.h"
+#include "./IssmMat.h"
+#include "./IssmSeqVec.h"
+#include "./IssmVec.h"
+#include "./IssmSolver.h"
+
+#ifdef _HAVE_MPI_
+#include "./IssmMpiDenseMat.h"
+#include "./IssmMpiVec.h"
+#endif
 
 #endif
Index: /issm/trunk/src/c/toolkits/mpi/mpiincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/mpiincludes.h	(revision 15395)
+++ /issm/trunk/src/c/toolkits/mpi/mpiincludes.h	(revision 15396)
@@ -6,4 +6,12 @@
 #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>
@@ -11,4 +19,5 @@
 /*Patches: */
 #include "./patches/mpipatches.h"
+#endif
 
 #endif
Index: /issm/trunk/src/c/toolkits/mpi/patches/DetermineGlobalSize.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/patches/DetermineGlobalSize.cpp	(revision 15396)
+++ /issm/trunk/src/c/toolkits/mpi/patches/DetermineGlobalSize.cpp	(revision 15396)
@@ -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,COMM comm){
+
+	/*output: */
+	int  global_size;
+
+	MPI_Reduce(&local_size, &global_size, 1, MPI_INT, MPI_SUM, 0, comm);
+	MPI_Bcast(&global_size,1,MPI_INT,0,comm);
+
+	return global_size;
+
+}
Index: /issm/trunk/src/c/toolkits/mpi/patches/DetermineLocalSize.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/patches/DetermineLocalSize.cpp	(revision 15395)
+++ /issm/trunk/src/c/toolkits/mpi/patches/DetermineLocalSize.cpp	(revision 15396)
@@ -6,5 +6,4 @@
 #include <math.h>
 #include "../../../shared/shared.h"
-#include "../../../include/types.h"
 
 int DetermineLocalSize(int global_size,COMM comm){
@@ -25,4 +24,12 @@
 	MPI_Comm_rank(comm,&my_rank);
 	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*/
Index: /issm/trunk/src/c/toolkits/mpi/patches/DetermineRowRankFromLocalSize.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/patches/DetermineRowRankFromLocalSize.cpp	(revision 15396)
+++ /issm/trunk/src/c/toolkits/mpi/patches/DetermineRowRankFromLocalSize.cpp	(revision 15396)
@@ -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,COMM comm){
+
+	/*intermediary: */
+	int i,j;
+	int my_rank=0;
+	int num_procs=0;
+	int lower_row,upper_row;
+
+	/*output: */
+	int* RowRank=NULL;
+
+	MPI_Comm_rank(comm,&my_rank);
+	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);
+	MPI_Allgather(&localsize,1,MPI_INT,alllocalsizes,1,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/patches/GetOwnershipBoundariesFromRange.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/patches/GetOwnershipBoundariesFromRange.cpp	(revision 15396)
+++ /issm/trunk/src/c/toolkits/mpi/patches/GetOwnershipBoundariesFromRange.cpp	(revision 15396)
@@ -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/Comm.h"
+
+void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range,COMM comm){
+
+	/*externals :*/
+	int my_rank;
+	int num_procs;
+
+	/*recover my_rank and num_procs:*/
+	MPI_Comm_size(comm,&num_procs);
+	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);
+	MPI_Allgather(&range,1,MPI_INT,allranges,1,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/patches/mpipatches.h
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/patches/mpipatches.h	(revision 15395)
+++ /issm/trunk/src/c/toolkits/mpi/patches/mpipatches.h	(revision 15396)
@@ -6,7 +6,11 @@
 #define MPI_PATCHES_H_
 
-#include "../../../include/types.h"
+#include "../../../shared/Numerics/types.h" 
+#include "../../../shared/io/Comm/Comm.h"
 
 int DetermineLocalSize(int global_size,COMM comm);
+int* DetermineRowRankFromLocalSize(int global_size,int localsize,COMM comm);
+void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range,COMM comm);
+int DetermineGlobalSize(int local_size,COMM comm);
 
 #endif
Index: /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp	(revision 15396)
+++ /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp	(revision 15396)
@@ -0,0 +1,160 @@
+/*!\file MpiDenseMumpsSolve.cpp
+ * \brief: solve dense matrix system with MUMPS
+ */
+
+/*Header files: {{{*/
+#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"
+#include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/io/Comm/Comm.h"
+#include "../mpi/patches/mpipatches.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){ /*{{{*/
+
+	/*Variables: {{{*/
+
+	MPI_Comm   comm;
+	int        my_rank;
+	int        num_procs;
+	int        i;
+	int        j;
+	int         nnz       ,local_nnz;
+	int        *irn_loc = NULL;
+	int        *jcn_loc = NULL;
+	IssmPDouble *a_loc   = NULL;
+	int         count;
+	int         lower_row;
+	int         upper_row;
+	IssmPDouble* rhs=NULL;
+	int*        recvcounts=NULL;
+	int*        displs=NULL;
+	/*}}}*/
+	/*Communicator info:{{{ */
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
+	comm=IssmComm::GetComm();
+	/*}}}*/
+	/*First, some checks:{{{ */
+	if (Kff_M!=Kff_N)_error_("stiffness matrix Kff should be square");
+	if (uf_M!=Kff_M | uf_M!=pf_M)_error_("solution vector should be the same size as stiffness matrix Kff and load vector pf");
+	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: */
+	local_nnz=0;
+	for(i=0;i<Kff_m;i++){
+		for(j=0;j<Kff_N;j++){
+			if (Kff[i*Kff_N+j]!=0)local_nnz++;
+		}
+	}
+
+	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;
+
+	/*Allocate: */
+	if(local_nnz){
+		irn_loc=xNew<int>(local_nnz);
+		jcn_loc=xNew<int>(local_nnz);
+		a_loc=xNew<IssmPDouble>(local_nnz);
+	}
+
+	/*Populate the triplets: */
+	GetOwnershipBoundariesFromRange(&lower_row,&upper_row,Kff_m,comm);
+	count=0;
+	for(i=0;i<Kff_m;i++){
+		for(j=0;j<Kff_N;j++){
+			if (Kff[i*Kff_N+j]!=0){
+				irn_loc[count]=lower_row+i+1; //fortran indexing
+				jcn_loc[count]=j+1; //fortran indexing
+				a_loc[count]=Kff[i*Kff_N+j];
+				count++;
+			}
+		}
+	}
+	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);
+
+	recvcounts=xNew<int>(num_procs);
+	displs=xNew<int>(num_procs);
+
+	/*recvcounts:*/
+	MPI_Allgather(&pf_m,1,MPI_INT,recvcounts,1,MPI_INT,comm);
+
+	/*displs: */
+	MPI_Allgather(&lower_row,1,MPI_INT,displs,1,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);
+	/*}}}*/
+	/*Now scatter from cpu 0 to all other cpus: {{{*/
+	MPI_Scatterv( rhs, recvcounts, displs, MPI_DOUBLE, uf, uf_m, 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<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!");
+} /*}}}*/
+#endif
Index: /issm/trunk/src/c/toolkits/mumps/mumpsincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/mumps/mumpsincludes.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/mumps/mumpsincludes.h	(revision 15396)
@@ -0,0 +1,10 @@
+/* \file mumpsincludes.h
+ * \brief all includes for MUMPS layer
+ */
+
+#ifndef _MUMPS_INCLUDES_H_
+#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);
+
+#endif
Index: /issm/trunk/src/c/toolkits/objects/Matrix.h
===================================================================
--- /issm/trunk/src/c/toolkits/objects/Matrix.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/objects/Matrix.h	(revision 15396)
@@ -0,0 +1,330 @@
+/*!\file:  Matrix.h
+ * \brief wrapper to matrix objects. The goal is to control which API (PETSc,Scalpack, Plapack?) 
+ * implements our underlying matrix format.
+ */ 
+
+#ifndef _MATRIX_H_
+#define _MATRIX_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <cstring>
+#include "../../shared/Enum/Enum.h"
+#include "../issm/issmtoolkit.h"
+/*}}}*/
+
+enum matrixtype { PetscMatType, IssmMatType };
+
+template <class doubletype> class Vector;
+
+template <class doubletype> 
+class Matrix{
+
+	public:
+
+		int       type;
+		#ifdef _HAVE_PETSC_
+		PetscMat              *pmatrix;
+		#endif
+		IssmMat<doubletype>   *imatrix;
+
+		/*Matrix constructors, destructors*/
+		/*FUNCTION Matrix(){{{*/
+		Matrix(){
+			InitCheckAndSetType();
+		}
+		/*}}}*/
+		/*FUNCTION Matrix(int M,int N){{{*/
+		Matrix(int M,int N){
+
+			InitCheckAndSetType();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(M,N);
+				#endif
+			}
+			else{
+				this->imatrix=new IssmMat<doubletype>(M,N);
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
+		Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz){
+
+			InitCheckAndSetType();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(m,n,M,N,d_nnz,o_nnz);
+				#endif
+			}
+			else{
+				this->imatrix=new IssmMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION Matrix(int M,int N,IssmDouble sparsity){{{*/
+		Matrix(int M,int N,double sparsity){
+
+			InitCheckAndSetType();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(M,N,sparsity);
+				#endif
+			}
+			else{
+				this->imatrix=new IssmMat<doubletype>(M,N,sparsity);
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Matrix(IssmDouble* serial_mat, int M,int N,IssmDouble sparsity){{{*/
+		Matrix(IssmPDouble* serial_mat,int M,int N,IssmPDouble sparsity){
+
+			InitCheckAndSetType();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(serial_mat,M,N,sparsity);
+				#endif
+			}
+			else{
+				this->imatrix=new IssmMat<doubletype>(serial_mat,M,N,sparsity);
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION Matrix(int M,int N,int connectivity,int numberofdofspernode){{{*/
+		Matrix(int M,int N,int connectivity,int numberofdofspernode){
+
+			InitCheckAndSetType();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(M,N,connectivity,numberofdofspernode);
+				#endif
+			}
+			else{
+				this->imatrix=new IssmMat<doubletype>(M,N,connectivity,numberofdofspernode);
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION ~Matrix(){{{*/
+		~Matrix(){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				delete this->pmatrix;
+				#endif
+			}
+			else delete this->imatrix;
+
+		}
+		/*}}}*/
+		/*FUNCTION InitCheckAndSetType(){{{*/
+		void InitCheckAndSetType(void){
+
+			char* toolkittype=NULL;
+
+			#ifdef _HAVE_PETSC_
+			pmatrix=NULL;
+			#endif
+			imatrix=NULL;
+
+			/*retrieve toolkittype: */
+			toolkittype=ToolkitOptions::GetToolkitType();
+
+			/*set matrix type: */
+			if (strcmp(toolkittype,"petsc")==0){
+				#ifdef _HAVE_PETSC_
+				type=PetscMatType; 
+				#else
+				_error_("cannot create petsc matrix without PETSC compiled!");
+				#endif
+			}
+			else if(strcmp(toolkittype,"issm")==0){
+				/*let this choice stand:*/
+				type=IssmMatType;
+			}
+			else _error_("unknow toolkit type ");
+
+			/*Free ressources: */
+			xDelete<char>(toolkittype);
+		}
+		/*}}}*/
+
+		/*Matrix specific routines:*/
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+			_assert_(this);
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->Echo();
+				#endif
+			}
+			else{
+				this->imatrix->Echo();
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION AllocationInfo{{{*/
+		void AllocationInfo(void){
+			_assert_(this);
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->AllocationInfo();
+				#endif
+			}
+			else{
+				//this->imatrix->AllocationInfo();
+				_error_("not supported yet");
+			}
+		}/*}}}*/
+		/*FUNCTION Assemble{{{*/
+		void Assemble(void){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->Assemble();
+				#endif
+			}
+			else{
+				this->imatrix->Assemble();
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Norm{{{*/
+		IssmDouble Norm(NormMode norm_type){
+
+			IssmDouble norm=0;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				norm=this->pmatrix->Norm(norm_type);
+				#endif
+			}
+			else{
+				norm=this->imatrix->Norm(norm_type);
+			}
+
+			return norm;
+		}
+		/*}}}*/
+		/*FUNCTION GetSize{{{*/
+		void GetSize(int* pM,int* pN){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->GetSize(pM,pN);
+				#endif
+			}
+			else{
+				this->imatrix->GetSize(pM,pN);
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION GetLocalSize{{{*/
+		void GetLocalSize(int* pM,int* pN){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->GetLocalSize(pM,pN);
+				#endif
+			}
+			else{
+				this->imatrix->GetLocalSize(pM,pN);
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION MatMult{{{*/
+		void MatMult(Vector<doubletype>* X,Vector<doubletype>* AX){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->MatMult(X->pvector,AX->pvector);
+				#endif
+			}
+			else{
+				this->imatrix->MatMult(X->ivector,AX->ivector);
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION Duplicate{{{*/
+		Matrix<doubletype>* Duplicate(void){
+
+			Matrix<doubletype>* output=new Matrix<doubletype>();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				output->pmatrix=this->pmatrix->Duplicate();
+				#endif
+			}
+			else{
+				output->imatrix=this->imatrix->Duplicate();
+			}
+
+			return output;
+		}
+		/*}}}*/
+		/*FUNCTION ToSerial{{{*/
+		doubletype* ToSerial(void){
+
+			doubletype* output=NULL;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				output=this->pmatrix->ToSerial();
+				#endif
+			}
+			else{
+				output=this->imatrix->ToSerial();
+			}
+
+			return output;
+		}
+		/*}}}*/
+		/*FUNCTION SetValues{{{*/
+		void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->SetValues(m,idxm,n,idxn,values,mode);
+				#endif
+			}
+			else{
+				this->imatrix->SetValues(m,idxm,n,idxn,values,mode);
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Convert{{{*/
+		void Convert(MatrixType newtype){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->Convert(newtype);
+				#endif
+			}
+			else{
+				this->imatrix->Convert(newtype);
+			}
+
+		}
+		/*}}}*/
+
+};
+
+#endif //#ifndef _MATRIX_H_
Index: /issm/trunk/src/c/toolkits/objects/Solver.h
===================================================================
--- /issm/trunk/src/c/toolkits/objects/Solver.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/objects/Solver.h	(revision 15396)
@@ -0,0 +1,85 @@
+/*!\file:  Solver.h
+ */ 
+
+#ifndef _SOLVER_CLASS_H_
+#define _SOLVER_CLASS_H_
+
+/*Headers:*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./Matrix.h"
+#include "./Vector.h"
+#include "../issm/issmtoolkit.h"
+class Parameters;
+
+template <class doubletype> 
+class Solver{
+
+	private:
+		Matrix<doubletype>* Kff;
+		Vector<doubletype>* pf;
+		Vector<doubletype>* uf0;
+		Vector<doubletype>* df;
+		Parameters* parameters;
+
+	public:
+		/*Constructors, destructors:*/
+		Solver(){/*{{{*/
+		}
+		/*}}}*/
+		Solver(Matrix<doubletype>* Kff_in, Vector<doubletype>* pf_in, Vector<doubletype>* uf0_in,Vector<doubletype>* df_in, Parameters* parameters_in){/*{{{*/
+
+			/*In debugging mode, check that stiffness matrix and load vectors are not NULL (they can be empty)*/
+			_assert_(Kff_in);
+			_assert_(pf_in);
+
+			/*initialize fields: */
+			this->Kff=Kff_in;
+			this->pf=pf_in;
+			this->uf0=uf0_in;
+			this->df=df_in;
+			this->parameters=parameters_in;
+		}
+		/*}}}*/
+		~Solver(){/*{{{*/
+		}
+		/*}}}*/
+
+		/*Methods: */
+		Vector<doubletype>* Solve(void){ /*{{{*/
+
+			/*output: */
+			Vector<doubletype>* uf=NULL;
+
+			/*Initialize vector: */
+			uf=new Vector<doubletype>();
+
+			/*According to matrix type, use specific solvers: */
+			switch(Kff->type){
+				#ifdef _HAVE_PETSC_
+				case PetscMatType:{
+					PetscVec* uf0_vector = NULL;
+					PetscVec* df_vector  = NULL;
+					if(uf0) uf0_vector = uf0->pvector;
+					if(df)  df_vector  = df->pvector;
+					PetscSolve(&uf->pvector,Kff->pmatrix,pf->pvector,uf0_vector,df_vector,parameters);
+					break;
+								  }
+				#endif
+				case IssmMatType:{
+					IssmSolve(&uf->ivector,Kff->imatrix,pf->ivector,parameters);
+					break;
+								 }
+				default:
+					_error_("Matrix type: " << Kff->type << " not supported yet!");
+			}
+
+			/*allocate output pointer: */
+			return uf;
+		}
+		/*}}}*/
+};
+#endif //#ifndef _SOLVER_H_
Index: /issm/trunk/src/c/toolkits/objects/Vector.h
===================================================================
--- /issm/trunk/src/c/toolkits/objects/Vector.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/objects/Vector.h	(revision 15396)
@@ -0,0 +1,357 @@
+/*!\file:  Vector.h
+ * \brief wrapper to vector objects. The goal is to control which API (PETSc,Scalpack, Plapack?) 
+ * implements our underlying vector format.
+ */ 
+
+#ifndef _VECTOR_H_
+#define _VECTOR_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <cstring>
+#include "../../shared/Enum/Enum.h"
+#include "../issm/issmtoolkit.h"
+/*}}}*/
+
+enum vectortype { PetscVecType, IssmVecType };
+
+template <class doubletype> 
+class Vector{
+
+	public:
+
+		int  type;
+		#ifdef _HAVE_PETSC_
+		PetscVec* pvector;
+		#endif
+		IssmVec<doubletype>* ivector; 
+
+		/*Vector constructors, destructors */
+		Vector(){ /*{{{*/
+
+			InitCheckAndSetType();
+		}
+		/*}}}*/
+		Vector(int M,bool fromlocalsize=false){ /*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector=new PetscVec(M,fromlocalsize);
+				#endif
+			}
+			else this->ivector=new IssmVec<doubletype>(M,fromlocalsize);
+
+		}
+		/*}}}*/
+		Vector(int m,int M){ /*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+					this->pvector=new PetscVec(m,M);
+				 #endif
+			}
+			else this->ivector=new IssmVec<doubletype>(m,M);
+		}
+		/*}}}*/
+		Vector(doubletype* serial_vec,int M){ /*{{{*/
+
+			InitCheckAndSetType();
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector=new PetscVec(serial_vec,M);
+				#endif
+			}
+			else this->ivector=new IssmVec<doubletype>(serial_vec,M);
+		}
+		/*}}}*/
+		~Vector(){ /*{{{*/
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				delete this->pvector;
+				#endif
+			}
+			else delete this->ivector;
+		}
+		/*}}}*/
+		#ifdef _HAVE_PETSC_
+		Vector(Vec petsc_vector){ /*{{{*/
+
+			this->type=PetscVecType;
+			this->ivector=NULL;
+			this->pvector=new PetscVec(petsc_vector);
+
+		}
+		/*}}}*/
+		#endif
+		void InitCheckAndSetType(void){ /*{{{*/
+
+			char* toolkittype=NULL;
+
+			#ifdef _HAVE_PETSC_
+			pvector=NULL;
+			#endif
+			ivector=NULL;
+
+			/*retrieve toolkittype: */
+			toolkittype=ToolkitOptions::GetToolkitType();
+
+			/*set vector type: */
+			if (strcmp(toolkittype,"petsc")==0){
+				#ifdef _HAVE_PETSC_
+				type=PetscVecType; 
+				#else
+				_error_("cannot create petsc vector without PETSC compiled!");
+				#endif
+			}
+			else if(strcmp(toolkittype,"issm")==0){
+				/*let this choice stand:*/
+				type=IssmVecType;
+			}
+			else _error_("unknow toolkit type ");
+
+			/*Free ressources: */
+			xDelete<char>(toolkittype);
+		}
+		/*}}}*/
+
+		/*Vector specific routines*/
+		/*FUNCTION Echo{{{*/
+		void Echo(void){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Echo();
+				#endif
+			}
+			else this->ivector->Echo();
+
+		}
+		/*}}}*/
+		/*FUNCTION Assemble{{{*/
+		void Assemble(void){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Assemble();
+				#endif
+			}
+			else this->ivector->Assemble();
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValues{{{*/
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){ _assert_(this);
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->SetValues(ssize,list,values,mode);
+				#endif
+			}
+			else this->ivector->SetValues(ssize,list,values,mode);
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValue{{{*/
+		void SetValue(int dof, doubletype value, InsMode mode){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->SetValue(dof,value,mode);
+				#endif
+			}
+			else this->ivector->SetValue(dof,value,mode);
+
+		}
+		/*}}}*/
+		/*FUNCTION GetValue{{{*/
+		void GetValue(doubletype* pvalue,int dof){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->GetValue(pvalue,dof);
+				#endif
+			}
+			else this->ivector->GetValue(pvalue,dof);
+
+		}
+		/*}}}*/
+		/*FUNCTION GetSize{{{*/
+		void GetSize(int* pM){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->GetSize(pM);
+				#endif
+			}
+			else this->ivector->GetSize(pM);
+
+		}
+		/*}}}*/
+		/*FUNCTION IsEmpty{{{*/
+		bool IsEmpty(void){
+			int M;
+
+			_assert_(this);
+			this->GetSize(&M);
+
+			if(M==0) 
+				return true;
+			else
+				return false;
+		}
+		/*}}}*/
+		/*FUNCTION GetLocalSize{{{*/
+		void GetLocalSize(int* pM){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->GetLocalSize(pM);
+				#endif
+			}
+			else this->ivector->GetLocalSize(pM);
+
+		}
+		/*}}}*/
+		/*FUNCTION Duplicate{{{*/
+		Vector<doubletype>* Duplicate(void){_assert_(this);
+
+			Vector<doubletype>* output=NULL;
+
+			output=new Vector<doubletype>();
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				output->pvector=this->pvector->Duplicate();
+				#endif
+			}
+			else output->ivector=this->ivector->Duplicate();
+
+			return output;
+
+		}
+		/*}}}*/
+		/*FUNCTION Set{{{*/
+		void Set(doubletype value){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Set(value);
+				#endif
+			}
+			else this->ivector->Set(value);
+
+		}
+		/*}}}*/
+		/*FUNCTION AXPY{{{*/
+		void AXPY(Vector* X, doubletype a){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->AXPY(X->pvector,a);
+				#endif
+			}
+			else this->ivector->AXPY(X->ivector,a);
+
+		}
+		/*}}}*/
+		/*FUNCTION AYPX{{{*/
+		void AYPX(Vector* X, doubletype a){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->AYPX(X->pvector,a);
+				#endif
+			}
+			else this->ivector->AYPX(X->ivector,a);
+		}
+		/*}}}*/
+		/*FUNCTION ToMPISerial{{{*/
+		doubletype* ToMPISerial(void){
+
+			doubletype* vec_serial=NULL;
+
+			_assert_(this);
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				vec_serial=this->pvector->ToMPISerial();
+				#endif
+			}
+			else vec_serial=this->ivector->ToMPISerial();
+
+			return vec_serial;
+
+		}
+		/*}}}*/
+		/*FUNCTION Copy{{{*/
+		void Copy(Vector* to){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Copy(to->pvector);
+				#endif
+			}
+			else this->ivector->Copy(to->ivector);
+		}
+		/*}}}*/
+		/*FUNCTION Norm{{{*/
+		doubletype Norm(NormMode norm_type){_assert_(this);
+
+			doubletype norm=0;
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				norm=this->pvector->Norm(norm_type);
+				#endif
+			}
+			else norm=this->ivector->Norm(norm_type);
+			return norm;
+		}
+		/*}}}*/
+		/*FUNCTION Scale{{{*/
+		void Scale(doubletype scale_factor){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Scale(scale_factor);
+				#endif
+			}
+			else this->ivector->Scale(scale_factor);
+		}
+		/*}}}*/
+		/*FUNCTION Dot{{{*/
+		doubletype Dot(Vector* vector){_assert_(this);
+
+			doubletype dot;
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				dot=this->pvector->Dot(vector->pvector);
+				#endif
+			}
+			else dot=this->ivector->Dot(vector->ivector);
+			return dot;
+		}
+		/*}}}*/
+		/*FUNCTION PointwiseDivide{{{*/
+		void PointwiseDivide(Vector* x,Vector* y){_assert_(this);
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->PointwiseDivide(x->pvector,y->pvector);
+				#endif
+			}
+			else this->ivector->PointwiseDivide(x->ivector,y->ivector);
+		}
+		/*}}}*/
+};
+#endif //#ifndef _VECTOR_H_
Index: /issm/trunk/src/c/toolkits/objects/toolkitobjects.h
===================================================================
--- /issm/trunk/src/c/toolkits/objects/toolkitobjects.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/objects/toolkitobjects.h	(revision 15396)
@@ -0,0 +1,13 @@
+
+/*!\file:  toolkitobjects.h
+ * \brief wrappers to toolkits
+ */ 
+
+#ifndef _TOOLKIT_OBJECTS_H_
+#define _TOOLKIT_OBJECTS_H_
+
+#include "./Vector.h"
+#include "./Matrix.h"
+#include "./Solver.h"
+
+#endif
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 15395)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 15396)
@@ -93,11 +93,12 @@
 	MatInfo info;
 	MatGetInfo(this->matrix,MAT_GLOBAL_SUM,&info);
-	_pprintLine_("=========================== Stiffness matrix allocation info ===========================");
-	_pprintLine_("");
-	_pprintLine_(" nz_allocated: "<<info.nz_allocated);
-	_pprintLine_(" nz_used     : "<<info.nz_used);
-	_pprintLine_(" nz_unneeded : "<<info.nz_unneeded<<" ("<<double(info.nz_unneeded)/double(info.nz_allocated)*100.<<"%)");
-	_pprintLine_("");
-	_pprintLine_("========================================================================================");
+	_printf0_("=========================== Stiffness matrix allocation info ===========================\n");
+	_printf0_("\n");
+   _printf0_(" Block size  : "<<info.block_size << "\n");
+	_printf0_(" nz_allocated: "<<info.nz_allocated << "\n");
+	_printf0_(" nz_used     : "<<info.nz_used << "\n");
+	_printf0_(" nz_unneeded : "<<info.nz_unneeded<<" ("<<double(info.nz_unneeded)/double(info.nz_allocated)*100.<<"%)\n");
+	_printf0_("\n");
+	_printf0_("========================================================================================\n");
 }
 /*}}}*/
@@ -176,5 +177,7 @@
 void PetscMat::SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){
 
-	MatSetValues(this->matrix,m,idxm,n,idxn,values,ISSMToPetscInsertMode(mode));
+	PetscErrorCode ierr;
+	ierr = MatSetValues(this->matrix,m,idxm,n,idxn,values,ISSMToPetscInsertMode(mode));
+	if(ierr) _error_("PETSC's MatSetValues reported an error");
 
 }
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.h	(revision 15395)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.h	(revision 15396)
@@ -17,5 +17,5 @@
 
 #include "../petscincludes.h"
-#include "../../../include/include.h"
+#include "../../../shared/Numerics/types.h"
 
 /*}}}*/
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 15396)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 15396)
@@ -0,0 +1,231 @@
+/*!\file SolverxPetsc
+ * \brief Petsc implementation of solver
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./PetscSolver.h"
+#include "../../../shared/Numerics/Verbosity.h"
+#include "../../../shared/MemOps/MemOps.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../shared/io/Comm/Comm.h"
+#include "../../../shared/Enum/Enum.h"
+
+void	PetscSolve(PetscVec** puf, PetscMat* Kff, PetscVec* pf, PetscVec* uf0,PetscVec* df, Parameters* parameters){ /*{{{*/
+
+	PetscVec* uf=new PetscVec();
+
+	Vec uf0_vector = NULL;
+	Vec df_vector  = NULL;
+
+	if(uf0) uf0_vector = uf0->vector;
+	if(df)  df_vector  = df->vector;
+
+	SolverxPetsc(&uf->vector, Kff->matrix, pf->vector, uf0_vector, df_vector, parameters);
+
+	*puf=uf;
+
+}
+/*}}}*/
+void	SolverxPetsc(Vec* puf, Mat Kff, Vec pf, Vec uf0,Vec df, Parameters* parameters){ /*{{{*/
+
+	/*Output: */
+	Vec        uf               = NULL;
+
+	/*Intermediary: */
+	int        local_m,local_n,global_m,global_n;
+
+	/*Solver */
+	KSP        ksp              = NULL;
+	PC         pc               = NULL;
+	int        iteration_number;
+	int        solver_type;
+	bool       fromlocalsize    = true;
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	PetscTruth flag,flg;
+	#else
+	PetscBool flag,flg;
+	#endif
+
+	/*Stokes: */
+	IS         isv=NULL;
+	IS         isp=NULL;
+
+	#if _PETSC_MAJOR_ >= 3 
+	char ksp_type[50];
+	#endif
+
+	/*Display message*/
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	if(VerboseSolver())PetscOptionsPrint(stdout);
+	#else
+	if(VerboseSolver())PetscOptionsView(PETSC_VIEWER_STDOUT_WORLD);
+	#endif
+
+	/*First, check that f-set is not NULL, i.e. model is fully constrained:*/ 
+	_assert_(Kff);
+	MatGetSize(Kff,&global_m,&global_n); _assert_(global_m==global_n);
+	if(!global_n){
+		*puf=NewVec(0,IssmComm::GetComm()); return;
+	}
+
+	/*Initial guess */
+	/*Now, check that we are not giving an initial guess to the solver, if we are running a direct solver: */
+	#if _PETSC_MAJOR_ >= 3 
+	PetscOptionsGetString(PETSC_NULL,"-ksp_type",ksp_type,49,&flg);
+	if (strcmp(ksp_type,"preonly")==0)uf0=NULL;
+	#endif
+
+	/*If initial guess for the solution exists, use it to create uf, otherwise, 
+	 * duplicate the right hand side so that the solution vector has the same structure*/
+	if(uf0){
+		VecDuplicate(uf0,&uf); VecCopy(uf0,uf);
+	}
+	else{
+		MatGetLocalSize(Kff,&local_m,&local_n);uf=NewVec(local_n,IssmComm::GetComm(),fromlocalsize);
+	}
+
+	/*Process petsc options to see if we are using special types of external solvers*/
+	PetscOptionsDetermineSolverType(&solver_type);
+
+	/*Check the solver is available*/
+	if(solver_type==MUMPSPACKAGE_LU || solver_type==MUMPSPACKAGE_CHOL){
+		#if _PETSC_MAJOR_ >=3
+			#ifndef _HAVE_MUMPS_
+			_error_("requested MUMPS solver, which was not compiled into ISSM!\n");
+			#endif
+		#endif
+	}
+
+	/*Prepare solver*/
+	KSPCreate(IssmComm::GetComm(),&ksp);
+	KSPSetOperators(ksp,Kff,Kff,DIFFERENT_NONZERO_PATTERN);
+	KSPSetFromOptions(ksp);
+
+	#if _PETSC_MAJOR_==3
+	/*Specific solver?: */
+	KSPGetPC(ksp,&pc);
+	if (solver_type==MUMPSPACKAGE_LU){
+		#if _PETSC_MINOR_==1
+		PCFactorSetMatSolverPackage(pc,MAT_SOLVER_MUMPS);
+		#else
+		PCFactorSetMatSolverPackage(pc,MATSOLVERMUMPS);
+		#endif
+	}
+
+	/*Stokes: */
+	if (solver_type==StokesSolverEnum){
+		/*Make indices out of doftypes: */
+		if(!df)_error_("need doftypes for Stokes solver!\n");
+		DofTypesToIndexSet(&isv,&isp,df,StokesSolverEnum);
+
+		/*Set field splits: */
+		KSPGetPC(ksp,&pc);
+		#if _PETSC_MINOR_==1
+		PCFieldSplitSetIS(pc,isv);
+		PCFieldSplitSetIS(pc,isp);
+		#else
+		PCFieldSplitSetIS(pc,PETSC_NULL,isv);
+		PCFieldSplitSetIS(pc,PETSC_NULL,isp);
+		#endif
+
+	}
+	#endif
+
+	/*If there is an initial guess for the solution, use it
+	 * except if we are using the MUMPS direct solver
+	 * where any initial guess will crash Petsc*/
+	if (uf0){
+		if((solver_type!=MUMPSPACKAGE_LU) && (solver_type!=MUMPSPACKAGE_CHOL) && (solver_type!=SPOOLESPACKAGE_LU) && (solver_type!=SPOOLESPACKAGE_CHOL) && (solver_type!=SUPERLUDISTPACKAGE)){
+			KSPSetInitialGuessNonzero(ksp,PETSC_TRUE);
+		}
+	}
+
+	/*Solve: */
+	if(VerboseSolver())KSPView(ksp,PETSC_VIEWER_STDOUT_WORLD);
+	KSPSolve(ksp,pf,uf);
+
+	/*Check convergence*/
+	KSPGetIterationNumber(ksp,&iteration_number);
+	if (iteration_number<0) _error_("Solver diverged at iteration number: " << -iteration_number);
+
+	/*Free resources:*/
+	KSPFree(&ksp);
+
+	/*Assign output pointers:*/
+	*puf=uf;
+} 
+/*}}}*/
+void DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum){ /*{{{*/
+
+	/*output: */
+	IS          isv=NULL;
+	IS          isp=NULL;
+
+	int         start,end;
+	IssmDouble*     df_local=NULL;
+	int         df_local_size;
+	int         i;
+
+	int*     pressure_indices=NULL;
+	int*     velocity_indices=NULL;
+	int      pressure_num=0;
+	int      velocity_num=0;
+	int      pressure_count=0;
+	int      velocity_count=0;
+
+	if(typeenum==StokesSolverEnum){
+
+		/*Ok, recover doftypes vector values and indices: */
+		VecGetOwnershipRange(df,&start,&end);
+		VecGetLocalSize(df,&df_local_size);
+		VecGetArray(df,&df_local);
+
+		pressure_num=0;
+		velocity_num=0;
+		for(i=0;i<df_local_size;i++){
+			if (df_local[i]==PressureEnum)pressure_num++;
+			else velocity_num++;
+		}
+
+		/*Allocate indices: */
+		if(pressure_num)pressure_indices=xNew<int>(pressure_num);
+		if(velocity_num)velocity_indices=xNew<int>(velocity_num);
+
+		pressure_count=0;
+		velocity_count=0;
+		for(i=0;i<df_local_size;i++){
+			if (df_local[i]==PressureEnum){
+				pressure_indices[pressure_count]=start+i;
+				pressure_count++;
+			}
+			if (df_local[i]==VelocityEnum){
+				velocity_indices[velocity_count]=start+i;
+				velocity_count++;
+			}
+		}
+		VecRestoreArray(df,&df_local);
+
+		/*Create indices sets: */
+		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+		ISCreateGeneral(IssmComm::GetComm(),pressure_num,pressure_indices,&isp);
+		ISCreateGeneral(IssmComm::GetComm(),velocity_num,velocity_indices,&isv);
+		#else
+		ISCreateGeneral(IssmComm::GetComm(),pressure_num,pressure_indices,PETSC_COPY_VALUES,&isp);
+		ISCreateGeneral(IssmComm::GetComm(),velocity_num,velocity_indices,PETSC_COPY_VALUES,&isv);
+		#endif
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(pressure_indices);
+	xDelete<int>(velocity_indices);
+
+	/*Assign output pointers:*/
+	*pisv=isv;
+	*pisp=isp;
+}
+/*}}}*/
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.h	(revision 15396)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.h	(revision 15396)
@@ -0,0 +1,24 @@
+/*!\file:  PetscMat.h
+ */ 
+
+#ifndef _PETSC_SOLVER_H_
+#define _PETSC_SOLVER_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../petscincludes.h"
+class Parameters;
+
+/*}}}*/
+
+void	PetscSolve(PetscVec** puf, PetscMat* Kff, PetscVec* pf, PetscVec* uf0,PetscVec* df, Parameters* parameters);
+void	SolverxPetsc(Vec* puf, Mat Kff, Vec pf, Vec uf0,Vec df, Parameters* parameters);
+void    DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum);
+
+#endif //#ifndef _PETSCSOLVER_H_
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.h	(revision 15395)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.h	(revision 15396)
@@ -17,5 +17,4 @@
 
 #include "../petscincludes.h"
-#include "../../../include/include.h"
 
 /*}}}*/
Index: /issm/trunk/src/c/toolkits/petsc/objects/petscobjects.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/petscobjects.h	(revision 15395)
+++ /issm/trunk/src/c/toolkits/petsc/objects/petscobjects.h	(revision 15396)
@@ -8,4 +8,5 @@
 #include "./PetscMat.h"
 #include "./PetscVec.h"
+#include "./PetscSolver.h"
 
 #endif
Index: sm/trunk/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp	(revision 15395)
+++ 	(revision )
@@ -1,44 +1,0 @@
-/*! \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/shared.h"
-
-void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range,COMM comm){
-
-	/*externals :*/
-	int my_rank;
-	int num_procs;
-
-	/*recover my_rank and num_procs:*/
-	MPI_Comm_size(comm,&num_procs);
-	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);
-	MPI_Allgather(&range,1,MPI_INT,allranges,1,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/petsc/patches/ISSMToPetscMatrixType.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 15395)
+++ /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 15396)
@@ -18,5 +18,5 @@
 #include "../../../shared/shared.h"
 
-const MatType ISSMToPetscMatrixType(MatrixType type){
+MatType ISSMToPetscMatrixType(MatrixType type){
 
 	switch(type){
Index: /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 15395)
+++ /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 15396)
@@ -17,5 +17,4 @@
 
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 #include "../../mpi/patches/mpipatches.h"
 
@@ -92,5 +91,5 @@
 
 	#if _PETSC_MAJOR_ >= 3 
-	#ifdef _HAVE_PETSCDEV_
+	#if defined(_HAVE_PETSCDEV_) || _PETSC_MINOR_ >=4
 	MatType type;
 	#else
Index: /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 15395)
+++ /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 15396)
@@ -17,5 +17,4 @@
 
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 
 void PetscOptionsDetermineSolverType(int* psolver_type){
Index: /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 15395)
+++ /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 15396)
@@ -17,5 +17,4 @@
 
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 
 void PetscOptionsInsertMultipleString(char* options_string){
Index: /issm/trunk/src/c/toolkits/petsc/patches/VecMerge.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 15395)
+++ /issm/trunk/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 15396)
@@ -17,5 +17,4 @@
 
 #include "../../../shared/shared.h"
-#include "../../../include/include.h"
 
 void VecMerge(Vec A, Vec B, double* row_partition_vector,int row_partition_size){
Index: /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 15395)
+++ /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 15396)
@@ -13,5 +13,5 @@
 #include "./SolverEnum.h"
 #include "../../toolkitsenums.h"
-#include "../../../include/types.h"
+#include "../../../shared/io/Comm/Comm.h"
 
 class Parameters;
@@ -38,5 +38,5 @@
 InsertMode ISSMToPetscInsertMode(InsMode mode);
 NormType ISSMToPetscNormMode(NormMode mode);
-const MatType ISSMToPetscMatrixType(MatrixType type);
+MatType ISSMToPetscMatrixType(MatrixType type);
 
 void PetscMatrixToDoubleMatrix(double** pmatrix, int* prows, int* pcols,Mat matrix);
Index: /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 15395)
+++ /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 15396)
@@ -2,5 +2,4 @@
  * \brief invert petsc matrix using Plapack
  */
-#include "../../../include/include.h"
 
 /* petsc: */
Index: /issm/trunk/src/c/toolkits/toolkits.h
===================================================================
--- /issm/trunk/src/c/toolkits/toolkits.h	(revision 15395)
+++ /issm/trunk/src/c/toolkits/toolkits.h	(revision 15396)
@@ -24,6 +24,19 @@
 #endif
 
+#ifdef _HAVE_GSL_
+#include "./gsl/gslincludes.h"
+#endif
+
+#ifdef _HAVE_ADOLC_
+#include "./adolc/adolcincludes.h"
+#endif
+
+#ifdef _HAVE_TRIANGLE_
 #include "./triangle/triangleincludes.h"
+#endif
+
+#include "./objects/toolkitobjects.h"
 #include "./toolkitsenums.h"
 #include "./issm/issmtoolkit.h"
+#include "./ToolkitOptions.h"
 #endif
Index: /issm/trunk/src/c/toolkits/toolkitsenums.h
===================================================================
--- /issm/trunk/src/c/toolkits/toolkitsenums.h	(revision 15395)
+++ /issm/trunk/src/c/toolkits/toolkitsenums.h	(revision 15396)
@@ -13,5 +13,5 @@
 
 typedef enum {INS_VAL, ADD_VAL} InsMode;
-typedef enum {NORM_INF,NORM_TWO} NormMode;
+typedef enum {NORM_INF,NORM_TWO,NORM_FROB} NormMode;
 typedef enum {DENSE_SEQUENTIAL,SPARSE_SEQUENTIAL} MatrixType;
 
Index: /issm/trunk/src/dox/issm.dox
===================================================================
--- /issm/trunk/src/dox/issm.dox	(revision 15395)
+++ /issm/trunk/src/dox/issm.dox	(revision 15396)
@@ -1,3 +1,2 @@
-
 /** 
   \mainpage ISSM C/C++ Source Code Browser
@@ -11,5 +10,5 @@
   
   These pages were automatically generated by <a href="http://www.doxygen.org/">doxygen</a>, 
-  from comments in the ISSM source code. 
+  from the ISSM source code. 
 
   Navigate the tabs above and browse through ISSM's 
@@ -25,9 +24,11 @@
   <B> Helpful Links </B>
 
-  - Fill out an ISSM download request <a href="http://issm.jpl.nasa.gov/installation/download/">here</a>.
+  - Download ISSM <a href="http://issm.jpl.nasa.gov/download/">here</a>.
 
-  - ISSM Installation instructions are found <a href="http://issm.jpl.nasa.gov/installation/installation/">here</a>.
+  - ISSM Installation instructions for Linux/Mac OSX are found <a href="http://issm.jpl.nasa.gov/download/unix/">here</a>.
+  
+  - ISSM Installation instructions for Windows are found <a href="http://issm.jpl.nasa.gov/download/windows/">here</a>.
 
-  - For help using ISSM, see our online <a href="http://issm.jpl.nasa.gov/doc_html/usersmanual.html">User's Manual</a>.
+  - For help using ISSM, see our online <a href="http://issm.jpl.nasa.gov/documentation/">Documentation</a>.
   Other documentation is also available including simple tutorials 
   and FAQ.
@@ -46,38 +47,44 @@
 </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;">14087</td><td  bgcolor=#FFFFFF style="text-align:right;">16669</td><td  bgcolor=#FFFFFF style="text-align:right;">56706</td><td  bgcolor=#FFFFFF style="text-align:right;">87462</td>
+<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>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">945</td><td  bgcolor=#C6E2FF style="text-align:right;">6583</td><td  bgcolor=#C6E2FF style="text-align:right;">13346</td><td  bgcolor=#C6E2FF style="text-align:right;">30647</td><td  bgcolor=#C6E2FF style="text-align:right;">50576</td>
+<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>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">362</td><td  bgcolor=#FFFFFF style="text-align:right;">2772</td><td  bgcolor=#FFFFFF style="text-align:right;">2894</td><td  bgcolor=#FFFFFF style="text-align:right;">11914</td><td  bgcolor=#FFFFFF style="text-align:right;">17580</td>
+<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>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> Python </th><td  bgcolor=#C6E2FF style="text-align:right;">109</td><td  bgcolor=#C6E2FF style="text-align:right;">3361</td><td  bgcolor=#C6E2FF style="text-align:right;">4763</td><td  bgcolor=#C6E2FF style="text-align:right;">7050</td><td  bgcolor=#C6E2FF style="text-align:right;">15174</td>
+<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>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> m4 </th><td  bgcolor=#FFFFFF style="text-align:right;">1</td><td  bgcolor=#FFFFFF style="text-align:right;">187</td><td  bgcolor=#FFFFFF style="text-align:right;">5</td><td  bgcolor=#FFFFFF style="text-align:right;">1247</td><td  bgcolor=#FFFFFF style="text-align:right;">1439</td>
+<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>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> Objective  C </th><td  bgcolor=#C6E2FF style="text-align:right;">9</td><td  bgcolor=#C6E2FF style="text-align:right;">96</td><td  bgcolor=#C6E2FF style="text-align:right;">0</td><td  bgcolor=#C6E2FF style="text-align:right;">370</td><td  bgcolor=#C6E2FF style="text-align:right;">466</td>
+<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;"> Bourne  Shell </th><td  bgcolor=#FFFFFF style="text-align:right;">5</td><td  bgcolor=#FFFFFF style="text-align:right;">57</td><td  bgcolor=#FFFFFF style="text-align:right;">79</td><td  bgcolor=#FFFFFF style="text-align:right;">256</td><td  bgcolor=#FFFFFF style="text-align:right;">392</td>
+<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;"> Perl </th><td  bgcolor=#C6E2FF style="text-align:right;">3</td><td  bgcolor=#C6E2FF style="text-align:right;">21</td><td  bgcolor=#C6E2FF style="text-align:right;">23</td><td  bgcolor=#C6E2FF style="text-align:right;">240</td><td  bgcolor=#C6E2FF style="text-align:right;">284</td>
+<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>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> IDL </th><td  bgcolor=#FFFFFF style="text-align:right;">1</td><td  bgcolor=#FFFFFF style="text-align:right;">18</td><td  bgcolor=#FFFFFF style="text-align:right;">4</td><td  bgcolor=#FFFFFF style="text-align:right;">124</td><td  bgcolor=#FFFFFF style="text-align:right;">146</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Objective  C </th><td  bgcolor=#FFFFFF style="text-align:right;">9</td><td  bgcolor=#FFFFFF style="text-align:right;">96</td><td  bgcolor=#FFFFFF style="text-align:right;">0</td><td  bgcolor=#FFFFFF style="text-align:right;">370</td><td  bgcolor=#FFFFFF style="text-align:right;">466</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> C </th><td  bgcolor=#C6E2FF style="text-align:right;">1</td><td  bgcolor=#C6E2FF style="text-align:right;">2</td><td  bgcolor=#C6E2FF style="text-align:right;">3</td><td  bgcolor=#C6E2FF style="text-align:right;">6</td><td  bgcolor=#C6E2FF style="text-align:right;">11</td>
+<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>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">1905</td><td  bgcolor=#FFFFFF style="text-align:right;">27184</td><td  bgcolor=#FFFFFF style="text-align:right;">37786</td><td  bgcolor=#FFFFFF style="text-align:right;">108560</td><td  bgcolor=#FFFFFF style="text-align:right;">173530</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Perl </th><td  bgcolor=#FFFFFF style="text-align:right;">1</td><td  bgcolor=#FFFFFF style="text-align:right;">6</td><td  bgcolor=#FFFFFF style="text-align:right;">9</td><td  bgcolor=#FFFFFF style="text-align:right;">196</td><td  bgcolor=#FFFFFF style="text-align:right;">211</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> 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>
+</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>
 </tr>
 </table>
 
-	<I> Copyright (C) 2012 </I>
+	<I> Copyright (C) 2013 </I>
   */
Index: /issm/trunk/src/m/Makefile.am
===================================================================
--- /issm/trunk/src/m/Makefile.am	(revision 15395)
+++ /issm/trunk/src/m/Makefile.am	(revision 15396)
@@ -22,5 +22,5 @@
 				 ./geometry/*.m \
 				 ./interp/*.m \
-				 ./latlong/*.m \
+				 ./coordsystems/*.m \
 				 ./mech/*.m \
 				 ./mesh/*.m \
Index: /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m	(revision 15395)
+++ /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m	(revision 15396)
@@ -16,4 +16,5 @@
 md.diagnostic.spcvz(pos)=0;
 md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
 
 %Dirichlet Values
Index: /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py	(revision 15395)
+++ /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py	(revision 15396)
@@ -22,4 +22,5 @@
 	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))
 
 	#Dirichlet Values
Index: /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m	(revision 15395)
+++ /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m	(revision 15396)
@@ -35,4 +35,5 @@
 md.diagnostic.spcvz(pos)=0;
 md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
 
 %Dirichlet Values
Index: /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py	(revision 15395)
+++ /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py	(revision 15396)
@@ -39,4 +39,5 @@
 	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))
 
 	#Dirichlet Values
Index: /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 15395)
+++ /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 15396)
@@ -42,4 +42,5 @@
 md.diagnostic.spcvz(pos)=0;
 md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
 
 %Dirichlet Values
Index: /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py	(revision 15395)
+++ /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py	(revision 15396)
@@ -47,4 +47,5 @@
 	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))
 
 	#Dirichlet Values
Index: /issm/trunk/src/m/classes/autodiff.m
===================================================================
--- /issm/trunk/src/m/classes/autodiff.m	(revision 15395)
+++ /issm/trunk/src/m/classes/autodiff.m	(revision 15396)
@@ -49,5 +49,5 @@
 			fielddisplay(obj,'driver','ADOLC driver (''fos_forward'' or ''fov_forward'')');
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 
 			WriteData(fid,'object',obj,'fieldname','isautodiff','format','Boolean');
Index: /issm/trunk/src/m/classes/autodiff.py
===================================================================
--- /issm/trunk/src/m/classes/autodiff.py	(revision 15395)
+++ /issm/trunk/src/m/classes/autodiff.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 from dependent import *
@@ -16,5 +15,4 @@
 	"""
 
-	#properties
 	def __init__(self,*args):    # {{{
 		self.isautodiff   = False
@@ -28,5 +26,4 @@
 			raise RuntimeError("constructor not supported")
 	# }}}
-
 	def __repr__(self):    # {{{
 		s ="      automatic differentiation parameters:\n"
@@ -39,9 +36,7 @@
 		return s
 	# }}}
-
 	def setdefaultparameters(self):    # {{{
 		return self
 	# }}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -61,6 +56,5 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','isautodiff','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','driver','format','String')
@@ -194,3 +188,2 @@
 		return
 	# }}}
-
Index: /issm/trunk/src/m/classes/balancethickness.m
===================================================================
--- /issm/trunk/src/m/classes/balancethickness.m	(revision 15395)
+++ /issm/trunk/src/m/classes/balancethickness.m	(revision 15396)
@@ -29,5 +29,5 @@
 			if solution~=BalancethicknessSolutionEnum(), return; end
 
-			md = checkfield(md,'balancethickness.spcthickness','forcing',1);
+			md = checkfield(md,'balancethickness.spcthickness');
 			md = checkfield(md,'balancethickness.thickening_rate','size',[md.mesh.numberofvertices 1],'NaN',1);
 			md = checkfield(md,'balancethickness.stabilization','size',[1 1],'values',[0 1 2 3]);
@@ -36,12 +36,15 @@
 			disp(sprintf('   balance thickness solution parameters:'));
 
-			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint)');
-			fielddisplay(obj,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt)');
+			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');
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
 			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','thickening_rate','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts);
 			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
 		end % }}}
Index: /issm/trunk/src/m/classes/balancethickness.py
===================================================================
--- /issm/trunk/src/m/classes/balancethickness.py	(revision 15395)
+++ /issm/trunk/src/m/classes/balancethickness.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -13,7 +12,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.spcthickness      = float('NaN')
 		self.thickening_rate   = float('NaN')
@@ -24,16 +21,14 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		
 		string='   balance thickness solution parameters:' 
 		
-		string="%s\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(self,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt)'))
+		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"))
 		return string
 		#}}}
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#Type of stabilization used
@@ -42,5 +37,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		#Early return
@@ -48,5 +42,5 @@
 			return md
 
-		md = checkfield(md,'balancethickness.spcthickness','forcing',1)
+		md = checkfield(md,'balancethickness.spcthickness')
 		md = checkfield(md,'balancethickness.thickening_rate','size',[md.mesh.numberofvertices],'NaN',1)
 		md = checkfield(md,'balancethickness.stabilization','size',[1],'values',[0,1,2,3])
@@ -54,9 +48,10 @@
 		return md
 	# }}}
+	def marshall(self,md,fid):    # {{{
 
-	def marshall(self,fid):    # {{{
+		yts=365.0*24.0*3600.0
+
 		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts)
 		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
 	# }}}
-
Index: /issm/trunk/src/m/classes/bamggeom.py
===================================================================
--- /issm/trunk/src/m/classes/bamggeom.py	(revision 15395)
+++ /issm/trunk/src/m/classes/bamggeom.py	(revision 15396)
@@ -32,5 +32,4 @@
 			raise TypeError("bamggeom constructor error message: unknown type of constructor call")
 	# }}}
-
 	def __repr__(self):    # {{{
 		s ="class '%s' object '%s' = \n" % (type(self),'self')
@@ -45,3 +44,2 @@
 		return s
 	# }}}
-
Index: /issm/trunk/src/m/classes/bamgmesh.py
===================================================================
--- /issm/trunk/src/m/classes/bamgmesh.py	(revision 15395)
+++ /issm/trunk/src/m/classes/bamgmesh.py	(revision 15396)
@@ -40,5 +40,4 @@
 			raise TypeError("bamgmesh constructor error message: unknown type of constructor call")
 	# }}}
-
 	def __repr__(self):    # {{{
 		s ="class '%s' object '%s' = \n" % (type(self),'self')
@@ -61,3 +60,2 @@
 		return s
 	# }}}
-
Index: /issm/trunk/src/m/classes/basalforcings.m
===================================================================
--- /issm/trunk/src/m/classes/basalforcings.m	(revision 15395)
+++ /issm/trunk/src/m/classes/basalforcings.m	(revision 15396)
@@ -38,13 +38,16 @@
 			disp(sprintf('   basal forcings parameters:'));
 
-			fielddisplay(obj,'melting_rate','basal melting rate (positive if melting)');
-			fielddisplay(obj,'melting_rate_correction','additional melting applied when the grounding line retreats');
+			fielddisplay(obj,'melting_rate','basal melting rate (positive if melting) [m/yr]');
+			fielddisplay(obj,'melting_rate_correction','additional melting applied to compensate for dh/dt [m/yr]');
 			fielddisplay(obj,'geothermalflux','geothermal heat flux [W/m^2]');
 
 		end % }}}
-		function marshall(obj,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','melting_rate','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','melting_rate_correction','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','geothermalflux','format','DoubleMat','mattype',1);
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'fieldname','melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',obj,'fieldname','melting_rate_correction','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/basalforcings.py
===================================================================
--- /issm/trunk/src/m/classes/basalforcings.py	(revision 15395)
+++ /issm/trunk/src/m/classes/basalforcings.py	(revision 15396)
@@ -1,7 +1,7 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
 from checkfield import *
 from WriteData import *
+import numpy
 
 class basalforcings(object):
@@ -13,7 +13,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.melting_rate             = float('NaN')
 		self.melting_rate_correction  = float('NaN')
@@ -24,18 +22,15 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string="   basal forcings parameters:"
 
-		string="%s\n%s"%(string,fielddisplay(self,"melting_rate","basal melting rate (positive if melting)"))
-		string="%s\n%s"%(string,fielddisplay(self,"melting_rate_correction","additional melting applied when the grounding line retreats"))
+		string="%s\n%s"%(string,fielddisplay(self,"melting_rate","basal melting rate (positive if melting) [m/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"melting_rate_correction","additional melting applied to compensate for dh/dt [m/yr]"))
 		string="%s\n%s"%(string,fielddisplay(self,"geothermalflux","geothermal heat flux [W/m^2]"))
 		return string
 		#}}}
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -52,9 +47,10 @@
 		return md
 	# }}}
+	def marshall(self,md,fid):    # {{{
 
-	def marshall(self,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','melting_rate','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','melting_rate_correction','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1)
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'object',self,'fieldname','melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','melting_rate_correction','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
 	# }}}
-
Index: /issm/trunk/src/m/classes/clusters/acenet.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/acenet.m	(revision 15395)
+++ /issm/trunk/src/m/classes/clusters/acenet.m	(revision 15396)
@@ -18,6 +18,6 @@
 		 time=10;
 		 % codepath='/usr/local/issm-r11321/bin'; % this one is for issm on acenet global
-		 codepath='PATH'; % this one is for issm on my acenet directory
-		 executionpath='/home/klemorza/issm/execution';
+		 codepath='/home/klemorza/issm/trunk-jpl/bin'; % this one is for issm on my acenet directory
+		 executionpath='/home/klemorza/issm/trunk-jpl/execution';
 		 %}}}
 	 end
@@ -66,5 +66,5 @@
 			 fprintf(fid,'#$ -cwd\n');
           fprintf(fid,'#$ -N issm\n');
-          fprintf(fid,'#$ -l h_rt=10:0:0\n');
+          fprintf(fid,'#$ -l h_rt=96:0:0\n');
           fprintf(fid,'#$ -pe ompi* %i\n',cluster.np);
           fprintf(fid,'#$ -j y\n');
Index: /issm/trunk/src/m/classes/clusters/cloud.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/cloud.m	(revision 15395)
+++ /issm/trunk/src/m/classes/clusters/cloud.m	(revision 15396)
@@ -54,6 +54,8 @@
 			fprintf(fid,'#!/bin/bash\n');
 			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);
 			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);
 			end
@@ -67,15 +69,21 @@
 				compressstring = [compressstring ' ' filelist{i}];
 			end
-			if cluster.interactive,
-				compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
-			end
 			system(compressstring);
 
+			if isempty(cluster.login),
+				error('cloud BuildQueueScript: login should be supplied!');
+			end
 			disp('uploading input file and queueing script');
 			issmstscpout(cluster.name,cluster.executionpath,cluster.login,{[dirname '.tar.gz']});
 
-			disp('launching solution sequence on remote cluster');
-			launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
-				' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
+			if cluster.interactive, 
+				disp('sending files to remote cluster. once done, please log into cluster and launch job');
+				launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+					' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz '];
+			else
+				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 '];
+			end
 			issmstssh(cluster.name,cluster.login,launchcommand);
 		end %}}}
Index: /issm/trunk/src/m/classes/clusters/discover.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/discover.m	(revision 15395)
+++ /issm/trunk/src/m/classes/clusters/discover.m	(revision 15396)
@@ -65,5 +65,5 @@
 
 			 if ( strcmpi(cluster.queue,'general') & cluster.cpuspernode*cluster.numnodes < 17)
-				 md = checkmessage(md,'cpus must be great than 17 for general queue');
+				 md = checkmessage(md,'cpus must be greater than 17 for general queue');
 			 end
 			 %now, check cluster.cpuspernode according to processor type
Index: /issm/trunk/src/m/classes/clusters/generic.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic.m	(revision 15395)
+++ /issm/trunk/src/m/classes/clusters/generic.m	(revision 15396)
@@ -114,9 +114,9 @@
 				fid=fopen([modelname '.bat'],'w');
 				fprintf(fid,'@echo off\n');
-				if cluster.interactive
-					fprintf(fid,'"%s/issm.exe" %s "%s" %s ',cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
-				else
-					fprintf(fid,'"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog',...
-						cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+
+				if cluster.np>1,
+					fprintf(fid,'"C:\\Program Files\\MPICH2\\bin\\mpiexec.exe" -n %i "%s/issm.exe" %s ./ %s ',cluster.np,cluster.codepath,EnumToString(solution),modelname);
+				else
+					fprintf(fid,'"%s/issm.exe" %s ./ %s ',cluster.codepath,EnumToString(solution),modelname);
 				end
 				fclose(fid);
@@ -178,21 +178,25 @@
 		function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
 
-			%compress the files into one zip.
-			compressstring=['tar -zcf ' dirname '.tar.gz '];
-			for i=1:numel(filelist),
-				compressstring = [compressstring ' ' filelist{i}];
-			end
-			if cluster.interactive,
-				compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
-			end
-			system(compressstring);
-
-			disp('uploading input file and queueing script');
-			issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
-
-			disp('launching solution sequence on remote cluster');
-			launchcommand=['source ' cluster.etcpath '/environment.sh && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
-				' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
-			issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+			if ~ispc,
+				%compress the files into one zip.
+				compressstring=['tar -zcf ' dirname '.tar.gz '];
+				for i=1:numel(filelist),
+					compressstring = [compressstring ' ' filelist{i}];
+				end
+				if cluster.interactive,
+					compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
+				end
+				system(compressstring);
+
+				disp('uploading input file and queueing script');
+				issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+				disp('launching solution sequence on remote cluster');
+				launchcommand=['source ' cluster.etcpath '/environment.sh && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+					' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
+				issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+			else
+				system([modelname '.bat']);
+			end
 		end %}}}
 		function Download(cluster,dirname,filelist)% {{{
Index: /issm/trunk/src/m/classes/clusters/generic.py
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic.py	(revision 15395)
+++ /issm/trunk/src/m/classes/clusters/generic.py	(revision 15396)
@@ -181,6 +181,6 @@
 
 		print 'launching solution sequence on remote cluster'
-		launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz  && source  %s.queue ' % \
-			(self.executionpath,dirname,dirname,dirname,dirname,dirname,modelname)
+		launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz  && chmod 777 %s.queue && ./%s.queue' % \
+			(self.executionpath,dirname,dirname,dirname,dirname,dirname,modelname,modelname)
 		issmssh(self.name,self.login,self.port,launchcommand)
 	# }}}
Index: /issm/trunk/src/m/classes/clusters/greenplanet.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/greenplanet.m	(revision 15395)
+++ /issm/trunk/src/m/classes/clusters/greenplanet.m	(revision 15396)
@@ -18,4 +18,5 @@
 		 executionpath='';
 		 interactive=0;
+		 time=24*60;
 	 end
 	 properties (SetAccess=private) 
@@ -61,4 +62,30 @@
 			 if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
 
+		 end
+		 %}}}
+		 function BuildKrigingQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %compute number of processors
+			 cluster.np=cluster.numnodes*cluster.cpuspernode;
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#PBS -S /bin/bash\n');
+			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -q %s \n',cluster.queue);
+			 fprintf(fid,'#PBS -l nodes=%i:ppn=%i\n',cluster.numnodes,cluster.cpuspernode);
+			 fprintf(fid,'#PBS -m bea\n');
+			 fprintf(fid,'#PBS -M mmorligh@uci.edu\n');
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
+			 %fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,dirname);
+			 fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
+			 if ~io_gather, %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+			 fclose(fid);
 		 end
 		 %}}}
Index: /issm/trunk/src/m/classes/clusters/pfe.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/pfe.m	(revision 15395)
+++ /issm/trunk/src/m/classes/clusters/pfe.m	(revision 15396)
@@ -60,7 +60,7 @@
 		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
-			 available_queues={'long','normal','debug'};
-			 queue_requirements_time=[5*24*60 8*60 2*60];
-			 queue_requirements_np=[2048 2048 150];
+			 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];
 
 			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
@@ -118,6 +118,6 @@
 			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
 			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
-			 fprintf(fid,'module load comp-intel/11.1.046\n');
-			 fprintf(fid,'module load mpi/mpt.1.25\n');
+			 fprintf(fid,'module load comp-intel/2013.1.117\n');
+			 fprintf(fid,'module load mpi-sgi/mpt.2.06rp16\n');
 			 fprintf(fid,'module load math/intel_mkl_64_10.0.011\n\n');
 			 fprintf(fid,'export PATH="$PATH:."\n\n');
@@ -164,11 +164,11 @@
 			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
 			 fprintf(fid,'#PBS -q %s \n',cluster.queue);
-			 fprintf(fid,'#PBS -W group_list=s1010\n');
+			 fprintf(fid,'#PBS -W group_list=%s\n',cluster.grouplist);
 			 fprintf(fid,'#PBS -m e\n');
 			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
 			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
 			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
-			 fprintf(fid,'module load comp-intel/11.1.046\n');
-			 fprintf(fid,'module load mpi/mpt.1.25\n');
+			 fprintf(fid,'module load comp-intel/2013.1.117\n');
+			 fprintf(fid,'module load mpi-sgi/mpt.2.06rp16\n');
 			 fprintf(fid,'module load math/intel_mkl_64_10.0.011\n\n');
 			 fprintf(fid,'export PATH="$PATH:."\n');
Index: /issm/trunk/src/m/classes/constants.m
===================================================================
--- /issm/trunk/src/m/classes/constants.m	(revision 15395)
+++ /issm/trunk/src/m/classes/constants.m	(revision 15396)
@@ -33,5 +33,5 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			md = checkfield(md,'constants.g','>',0,'size',[1 1]);
+%			md = checkfield(md,'constants.g','>',0,'size',[1 1]);
 			md = checkfield(md,'constants.yts','>',0,'size',[1 1]);
 			md = checkfield(md,'constants.referencetemperature','size',[1 1]);
@@ -41,10 +41,10 @@
 			disp(sprintf('   constants parameters:'));
 
-			fielddisplay(obj,'g','gravitational acceleration');
-			fielddisplay(obj,'yts','number of seconds in a year');
-			fielddisplay(obj,'referencetemperature','reference temperature used in the enthalpy model');
+			fielddisplay(obj,'g','gravitational acceleration [m/s^2]');
+			fielddisplay(obj,'yts','number of seconds in a year [s/yr]');
+			fielddisplay(obj,'referencetemperature','reference temperature used in the enthalpy model [K]');
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','g','format','Double');
 			WriteData(fid,'object',obj,'fieldname','yts','format','Double');
Index: /issm/trunk/src/m/classes/constants.py
===================================================================
--- /issm/trunk/src/m/classes/constants.py	(revision 15395)
+++ /issm/trunk/src/m/classes/constants.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -13,7 +12,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.g                    = 0
 		self.yts                  = 0
@@ -24,16 +21,14 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string="   constants parameters:"
 
-		string="%s\n%s"%(string,fielddisplay(self,"g","gravitational acceleration"))
-		string="%s\n%s"%(string,fielddisplay(self,"yts","number of seconds in a year"))
-		string="%s\n%s"%(string,fielddisplay(self,"referencetemperature","reference temperature used in the enthalpy model"))
+		string="%s\n%s"%(string,fielddisplay(self,"g","gravitational acceleration [m/s^2]"))
+		string="%s\n%s"%(string,fielddisplay(self,"yts","number of seconds in a year [s/yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"referencetemperature","reference temperature used in the enthalpy model [K]"))
 
 		return string
 		#}}}
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#acceleration due to gravity (m/s^2)
@@ -48,5 +43,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -57,9 +51,7 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','g','format','Double')
 		WriteData(fid,'object',self,'fieldname','yts','format','Double')
 		WriteData(fid,'object',self,'fieldname','referencetemperature','format','Double')
 	# }}}
-
Index: /issm/trunk/src/m/classes/debug.m
===================================================================
--- /issm/trunk/src/m/classes/debug.m	(revision 15395)
+++ /issm/trunk/src/m/classes/debug.m	(revision 15396)
@@ -30,5 +30,5 @@
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','profiling','format','Boolean');
 		end % }}}
Index: /issm/trunk/src/m/classes/debug.py
===================================================================
--- /issm/trunk/src/m/classes/debug.py	(revision 15395)
+++ /issm/trunk/src/m/classes/debug.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from WriteData import *
@@ -11,7 +10,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.valgrind  = False
 		self.gprof     = False
@@ -22,6 +19,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string="   debug parameters:"
 
@@ -31,12 +27,8 @@
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','profiling','format','Boolean')
 	# }}}
-
Index: /issm/trunk/src/m/classes/dependent.py
===================================================================
--- /issm/trunk/src/m/classes/dependent.py	(revision 15395)
+++ /issm/trunk/src/m/classes/dependent.py	(revision 15396)
@@ -47,5 +47,4 @@
 			self.segments=MeshProfileIntersection(mesh.elements,mesh.x,mesh.y,self.exp)
 	# }}}
-
 	def __repr__(self):    # {{{
 		s ="   dependent variable:\n"
@@ -62,10 +61,8 @@
 		return s
 	# }}}
-
 	def setdefaultparameters(self):    # {{{
 		#do nothing
 		return self
 	# }}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		if strcmpi(self.name,'MassFlux'):
@@ -83,5 +80,4 @@
 		return md
 	# }}}
-
 	def typetoscalar(self):    # {{{
 		if   strcmpi(self.type,'scalar'):
@@ -92,3 +88,2 @@
 		return scalar
 	# }}}
-
Index: /issm/trunk/src/m/classes/diagnostic.m
===================================================================
--- /issm/trunk/src/m/classes/diagnostic.m	(revision 15395)
+++ /issm/trunk/src/m/classes/diagnostic.m	(revision 15396)
@@ -23,4 +23,5 @@
 		rift_penalty_threshold   = 0;
 		referential              = NaN;
+		loadingforce             = NaN;
 		requested_outputs        = NaN;
 	end
@@ -76,5 +77,5 @@
 			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]);
+			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);
@@ -87,4 +88,5 @@
 			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]);
@@ -120,15 +122,15 @@
 			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','Apply Newton''s method instead of a Picard fixed point method');
+			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)');
-			fielddisplay(obj,'spcvy','y-axis velocity constraint (NaN means no constraint)');
-			fielddisplay(obj,'spcvz','z-axis velocity constraint (NaN means no constraint)');
-			fielddisplay(obj,'icefront','segments on ice front list (last column 0-> Air, 1-> Water, 2->Ice)');
+			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:'));
@@ -144,15 +146,16 @@
 			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,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','spcvx','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','spcvy','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','spcvz','format','DoubleMat','mattype',1);
+		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','Boolean');
+			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');
@@ -164,4 +167,7 @@
 			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);
 
Index: /issm/trunk/src/m/classes/diagnostic.py
===================================================================
--- /issm/trunk/src/m/classes/diagnostic.py	(revision 15395)
+++ /issm/trunk/src/m/classes/diagnostic.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 import sys
@@ -16,7 +15,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.spcvx                    = float('NaN')
 		self.spcvy                    = float('NaN')
@@ -36,4 +33,5 @@
 		self.rift_penalty_threshold   = 0
 		self.referential              = float('NaN')
+		self.loadingforce             = float('NaN')
 		self.requested_outputs        = float('NaN')
 
@@ -42,23 +40,20 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	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',"Apply Newton's method instead of a Picard fixed point method"))
+		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)'))
-		string="%s\n%s"%(string,fielddisplay(self,'spcvy','y-axis velocity constraint (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(self,'spcvz','z-axis velocity constraint (NaN means no constraint)'))
-		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,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:')
@@ -74,11 +69,10 @@
 		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):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		#maximum of non-linear iterations.
 		self.maxiter=100
@@ -110,5 +104,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -126,5 +119,5 @@
 		md = checkfield(md,'diagnostic.reltol','size',[1])
 		md = checkfield(md,'diagnostic.abstol','size',[1])
-		md = checkfield(md,'diagnostic.isnewton','numel',[1],'values',[0,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)
@@ -136,4 +129,5 @@
 		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])
@@ -166,13 +160,12 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','spcvx','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','spcvy','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','spcvz','format','DoubleMat','mattype',1)
+	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','Boolean')
+		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')
@@ -184,4 +177,7 @@
 		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)
 
@@ -193,3 +189,2 @@
 		WriteData(fid,'data',data,'enum',DiagnosticIcefrontEnum(),'format','DoubleMat','mattype',3)
 	# }}}
-
Index: /issm/trunk/src/m/classes/flaim.py
===================================================================
--- /issm/trunk/src/m/classes/flaim.py	(revision 15395)
+++ /issm/trunk/src/m/classes/flaim.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 from collections import OrderedDict
@@ -15,7 +14,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.targets            = ''
 		self.tracks             = ''
@@ -32,6 +29,5 @@
 		self.opt_niter          = 30000
 		#}}}
-	def __repr__(self):
-		# {{{ Displa
+	def __repr__(self): # {{{
 		string='   FLAIM - Flight Line Adaptation using Ice sheet Modeling:'
 
@@ -61,5 +57,4 @@
 		return string
 		#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -76,3 +71,2 @@
 		return md
 	# }}}
-
Index: /issm/trunk/src/m/classes/flowequation.m
===================================================================
--- /issm/trunk/src/m/classes/flowequation.m	(revision 15395)
+++ /issm/trunk/src/m/classes/flowequation.m	(revision 15396)
@@ -73,5 +73,5 @@
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','ismacayealpattyn','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','ishutter','format','Boolean');
Index: /issm/trunk/src/m/classes/flowequation.py
===================================================================
--- /issm/trunk/src/m/classes/flowequation.py	(revision 15395)
+++ /issm/trunk/src/m/classes/flowequation.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 import copy
@@ -15,7 +14,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		
 		self.ismacayealpattyn     = 0
@@ -33,6 +30,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string='   flow equation parameters:'
 
@@ -48,10 +44,7 @@
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -80,6 +73,5 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','ismacayealpattyn','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','ishutter','format','Boolean')
@@ -113,3 +105,2 @@
 		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 15395)
+++ /issm/trunk/src/m/classes/friction.m	(revision 15396)
@@ -37,5 +37,5 @@
 			fielddisplay(obj,'q','q exponent');
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','coefficient','format','DoubleMat','mattype',1);
 			WriteData(fid,'object',obj,'fieldname','p','format','DoubleMat','mattype',2);
Index: /issm/trunk/src/m/classes/friction.py
===================================================================
--- /issm/trunk/src/m/classes/friction.py	(revision 15395)
+++ /issm/trunk/src/m/classes/friction.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -13,7 +12,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.coefficient = float('NaN')
 		self.p           = float('NaN')
@@ -24,6 +21,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string="Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p"
 
@@ -33,10 +29,7 @@
 		return string
 		#}}}
-
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -51,9 +44,7 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1)
 		WriteData(fid,'object',self,'fieldname','p','format','DoubleMat','mattype',2)
 		WriteData(fid,'object',self,'fieldname','q','format','DoubleMat','mattype',2)
 	# }}}
-
Index: /issm/trunk/src/m/classes/geometry.m
===================================================================
--- /issm/trunk/src/m/classes/geometry.m	(revision 15395)
+++ /issm/trunk/src/m/classes/geometry.m	(revision 15396)
@@ -26,12 +26,16 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			md = checkfield(md,'geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
-			md = checkfield(md,'geometry.bed'      ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
-			md = checkfield(md,'geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices 1],'>',0);
-			if any((obj.thickness-obj.surface+obj.bed)>10^-9),
-				md = checkmessage(md,['equality thickness=surface-bed violated']);
-			end 
-			if solution==TransientSolutionEnum() & md.transient.isgroundingline,
-				md = checkfield(md,'geometry.bathymetry','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			if (solution==TransientSolutionEnum() & md.transient.isgia) | (solution==GiaSolutionEnum()),
+				md = checkfield(md,'geometry.thickness','forcing',1,'NaN',1,'>=',0);
+			else
+				md = checkfield(md,'geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'geometry.bed'      ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices 1],'>',0);
+				if any((obj.thickness-obj.surface+obj.bed)>10^-9),
+					md = checkmessage(md,['equality thickness=surface-bed violated']);
+				end 
+				if solution==TransientSolutionEnum() & md.transient.isgroundingline,
+					md = checkfield(md,'geometry.bathymetry','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				end
 			end
 		end % }}}
@@ -39,14 +43,14 @@
 			disp(sprintf('   geometry parameters:'));
 
-			fielddisplay(obj,'surface','surface elevation');
-			fielddisplay(obj,'thickness','ice thickness');
-			fielddisplay(obj,'bed','bed elevation');
-			fielddisplay(obj,'bathymetry','bathymetry elevation');
+			fielddisplay(obj,'surface','surface elevation [m]');
+			fielddisplay(obj,'thickness','ice thickness [m]');
+			fielddisplay(obj,'bed','bed elevation [m]');
+			fielddisplay(obj,'bathymetry','bathymetry elevation [m]');
 			fielddisplay(obj,'hydrostatic_ratio','coefficient for ice shelves'' thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro');
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'data',obj.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum());
-			WriteData(fid,'data',obj.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum());
+			WriteData(fid,'data',obj.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum(),'forcinglength',md.mesh.numberofvertices+1);
 			WriteData(fid,'data',obj.bed,'format','DoubleMat','mattype',1,'enum',BedEnum());
 			WriteData(fid,'data',obj.bathymetry,'format','DoubleMat','mattype',1,'enum',BathymetryEnum());
Index: /issm/trunk/src/m/classes/geometry.py
===================================================================
--- /issm/trunk/src/m/classes/geometry.py	(revision 15395)
+++ /issm/trunk/src/m/classes/geometry.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -13,7 +12,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.surface           = float('NaN')
 		self.thickness         = float('NaN')
@@ -26,27 +23,22 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 
 		string="   geometry parameters:"
-
-		string="%s\n%s"%(string,fielddisplay(self,'surface','surface elevation'))
-		string="%s\n%s"%(string,fielddisplay(self,'thickness','ice thickness'))
-		string="%s\n%s"%(string,fielddisplay(self,'bed','bed elevation'))
-		string="%s\n%s"%(string,fielddisplay(self,'bathymetry','bathymetry elevation'))
+		string="%s\n%s"%(string,fielddisplay(self,'surface','surface elevation [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickness','ice thickness [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'bed','bed elevation [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'bathymetry','bathymetry elevation [m]'))
 		string="%s\n%s"%(string,fielddisplay(self,'hydrostatic_ratio','coefficient for ice shelves'' thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro'))
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
 		md = checkfield(md,'geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices])
 		md = checkfield(md,'geometry.bed'      ,'NaN',1,'size',[md.mesh.numberofvertices])
-		md = checkfield(md,'geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices],'>',0)
+		md = checkfield(md,'geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices],'>',0,'forcing',1)
 		if any((self.thickness-self.surface+self.bed)>10**-9):
 			md.checkmessage("equality thickness=surface-bed violated")
@@ -56,11 +48,9 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'data',self.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum())
-		WriteData(fid,'data',self.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum())
+		WriteData(fid,'data',self.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum(),'forcinglength',md.mesh.numberofvertices+1)
 		WriteData(fid,'data',self.bed,'format','DoubleMat','mattype',1,'enum',BedEnum())
 		WriteData(fid,'data',self.bathymetry,'format','DoubleMat','mattype',1,'enum',BathymetryEnum())
 		WriteData(fid,'object',self,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1)
 	# }}}
-
Index: /issm/trunk/src/m/classes/gia.m
===================================================================
--- /issm/trunk/src/m/classes/gia.m	(revision 15396)
+++ /issm/trunk/src/m/classes/gia.m	(revision 15396)
@@ -0,0 +1,61 @@
+%GIA class definition
+%
+%   Usage:
+%      gia=gia();
+
+classdef gia
+	properties (SetAccess=public) 
+		mantle_viscosity              = NaN;
+		lithosphere_thickness         = NaN;
+		cross_section_shape           = 0;
+	end
+	methods
+		function obj = gia(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+		obj.cross_section_shape=1; %square as default (see iedge in GiaDeflectionCorex)
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ~ismember(GiaAnalysisEnum(),analyses), return; end
+			md = checkfield(md,'gia.mantle_viscosity','NaN',1,'size',[md.mesh.numberofvertices 1],'>',0);
+			md = checkfield(md,'gia.lithosphere_thickness','NaN',1,'size',[md.mesh.numberofvertices 1],'>',0);
+			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 
+			%are not provided into the future.
+			if solution==TransientSolutionEnum() & md.transient.isprognostic & 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'...
+							' for the gia model should not be provided in the future.'...
+							' Synchronize your start_time to correspond to the most recent transient'...
+							' thickness forcing timestep']);
+					end
+				end
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   gia parameters:'));
+
+			fielddisplay(obj,'mantle_viscosity','mantle viscosity[Pa s]');
+			fielddisplay(obj,'lithosphere_thickness','lithosphere thickness (km)');
+			fielddisplay(obj,'cross_section_shape','1: square-edged (default). 2: elliptical.  See iedge in GiaDeflectionCore');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','mantle_viscosity','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','lithosphere_thickness','format','DoubleMat','mattype',1,'scale',10^3); %from km to m
+			WriteData(fid,'object',obj,'fieldname','cross_section_shape','format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/gia.py
===================================================================
--- /issm/trunk/src/m/classes/gia.py	(revision 15396)
+++ /issm/trunk/src/m/classes/gia.py	(revision 15396)
@@ -0,0 +1,58 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
+
+class gia(object):
+	"""
+	GIA class definition
+
+	   Usage:
+	      gia=gia();
+	"""
+
+	def __init__(self): # {{{
+		self.mantle_viscosity              = float('NaN');
+		self.lithosphere_thickness         = float('NaN');
+		self.cross_section_shape           = 0;
+	
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		
+		string='   gia solution parameters:' 
+		
+		string="%s\n%s"%(string,fielddisplay(self,'mantle_viscosity','mantle viscosity constraints (NaN means no constraint) (Pa s)'))
+		string="%s\n%s"%(string,fielddisplay(self,'lithosphere_thickness','lithosphere thickness constraints (NaN means no constraint) (m)'))
+		string="%s\n%s"%(string,fielddisplay(self,'cross_section_shape',"1: square-edged, 2: elliptical-edged surface"))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+
+		self.cross_section_shape=1; 
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		# Early return 
+		if (GiaAnalysisEnum() not in  analyses):
+			return md 
+		
+		md = checkfield(md,'gia.mantle_viscosity','NaN',1,'size',[md.mesh.numberofvertices,1],'>',0)
+		md = checkfield(md,'gia.lithosphere_thickness','NaN',1,'size',[md.mesh.numberofvertices,1],'>',0)
+		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 
+		#are not provided into the future.
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		WriteData(fid,'object',self,'fieldname','mantle_viscosity','format','DoubleMat','mattype',1);
+		WriteData(fid,'object',self,'fieldname','lithosphere_thickness','format','DoubleMat','mattype',1,'scale',10.**3.);
+		WriteData(fid,'object',self,'fieldname','cross_section_shape','format','Integer');
+	# }}}
Index: /issm/trunk/src/m/classes/groundingline.m
===================================================================
--- /issm/trunk/src/m/classes/groundingline.m	(revision 15395)
+++ /issm/trunk/src/m/classes/groundingline.m	(revision 15396)
@@ -1,3 +1,3 @@
-%CONSTANTS class definition
+%GROUNDINGLINE class definition
 %
 %   Usage:
@@ -29,5 +29,5 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			md = checkfield(md,'groundingline.migration','values',{'None' 'AgressiveMigration' 'SoftMigration'});
+			md = checkfield(md,'groundingline.migration','values',{'None' 'AgressiveMigration' 'SoftMigration' 'SubelementMigration','SubelementMigration2'});
 
 			if ~strcmp(obj.migration,'None'),
@@ -47,11 +47,10 @@
 		end % }}}
 		function disp(obj) % {{{
-			disp(sprintf('   balance thickness solution parameters:'));
-
+			disp(sprintf('   grounding line migration parameters:'));
 			fielddisplay(obj,'migration','type of grounding line migration: ''SoftMigration'',''AgressiveMigration'' or ''None''');
-			fielddisplay(obj,'melting_rate','melting rate applied when previously grounded parts start floating');
+			fielddisplay(obj,'melting_rate','melting rate applied when previously grounded parts start floating [m/yr]');
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'data',StringToEnum(obj.migration),'enum',GroundinglineMigrationEnum(),'format','Integer');
 			WriteData(fid,'object',obj,'fieldname','melting_rate','format','Double');
Index: /issm/trunk/src/m/classes/groundingline.py
===================================================================
--- /issm/trunk/src/m/classes/groundingline.py	(revision 15395)
+++ /issm/trunk/src/m/classes/groundingline.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 from fielddisplay import fielddisplay
@@ -10,5 +9,5 @@
 class groundingline(object):
 	"""
-	CONSTANTS class definition
+	GROUNDINGLINE class definition
 
 	   Usage:
@@ -16,7 +15,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.migration=''
 		self.melting_rate=float('NaN')
@@ -26,14 +23,12 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
-		string='   grounding line solution parameters:'
+	def __repr__(self): # {{{
+		string='   grounding line migration parameters:'
 
 		string="%s\n%s"%(string,fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''AgressiveMigration'' or ''None'''))
-		string="%s\n%s"%(string,fielddisplay(self,'melting_rate','melting rate applied when previously grounded parts start floating'))
+		string="%s\n%s"%(string,fielddisplay(self,'melting_rate','melting rate applied when previously grounded parts start floating [m/yr]'))
 		return string
 		#}}}	
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 
 		#Type of migration
@@ -45,8 +40,7 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
-		md = checkfield(md,'groundingline.migration','values',['None','AgressiveMigration','SoftMigration'])
+		md = checkfield(md,'groundingline.migration','values',['None','AgressiveMigration','SoftMigration','SubelementMigration','SubelementMigration2'])
 
 		if not strcmp(self.migration,'None'):
@@ -62,8 +56,6 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'data',StringToEnum(self.migration)[0],'enum',GroundinglineMigrationEnum(),'format','Integer')
 		WriteData(fid,'object',self,'fieldname','melting_rate','format','Double')
 	# }}}
-
Index: sm/trunk/src/m/classes/hydrology.m
===================================================================
--- /issm/trunk/src/m/classes/hydrology.m	(revision 15395)
+++ 	(revision )
@@ -1,67 +1,0 @@
-%HYDROLOGY class definition
-%
-%   Usage:
-%      hydrology=hydrology();
-
-classdef hydrology
-	properties (SetAccess=public) 
-		spcwatercolumn = NaN;
-		n              = 0;
-		CR             = 0;
-		p              = 0;
-		q              = 0;
-		kn             = 0;
-		stabilization  = 0;
-	end
-	methods
-		function obj = hydrology(varargin) % {{{
-			switch nargin
-				case 0
-					obj=setdefaultparameters(obj);
-				otherwise
-					error('constructor not supported');
-			end
-		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
-
-			%Parameters from Johnson's 2002 thesis, section 3.5.4			 
-			obj.n=.02;			 
-			obj.CR=.01;
-			obj.p=2;		 
-			obj.q=1;		 
-			obj.kn=0;
-
-			%Type of stabilization to use 0:nothing 1:artificial_diffusivity
-			obj.stabilization=1;
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
-
-			%Early return
-			if ~ismember(HydrologyAnalysisEnum(),analyses), return; end
-
-			md = checkfield(md,'hydrology.spcwatercolumn','forcing',1);
-			md = checkfield(md,'hydrology.stabilization','>=',0);
-		end % }}}
-		function disp(obj) % {{{
-			disp(sprintf('   hydrology solution parameters:'));
-
-			fielddisplay(obj,'spcwatercolumn','water thickness constraints (NaN means no constraint)');
-			fielddisplay(obj,'n','Manning roughness coefficient');
-			fielddisplay(obj,'CR','tortuosity parameter');
-			fielddisplay(obj,'p','dimensionless exponent in Manning velocity formula');
-			fielddisplay(obj,'q','dimensionless exponent in Manning velocity formula');
-			fielddisplay(obj,'kn','parameter in effective pressure formula');
-			fielddisplay(obj,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.');
-
-		end % }}}
-		function marshall(obj,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','n','format','Double');
-			WriteData(fid,'object',obj,'fieldname','CR','format','Double');
-			WriteData(fid,'object',obj,'fieldname','p','format','Double');
-			WriteData(fid,'object',obj,'fieldname','q','format','Double');
-			WriteData(fid,'object',obj,'fieldname','kn','format','Double');
-			WriteData(fid,'object',obj,'fieldname','stabilization','format','Double');
-		end % }}}
-	end
-end
Index: sm/trunk/src/m/classes/hydrology.py
===================================================================
--- /issm/trunk/src/m/classes/hydrology.py	(revision 15395)
+++ 	(revision )
@@ -1,81 +1,0 @@
-#module imports
-from fielddisplay import fielddisplay
-from EnumDefinitions import *
-from checkfield import *
-from WriteData import *
-
-class hydrology(object):
-	"""
-	HYDROLOGY class definition
-
-	   Usage:
-	      hydrology=hydrology();
-	"""
-
-	#properties
-	def __init__(self):
-		# {{{ Properties
-		self.spcwatercolumn = float('NaN')
-		self.n              = 0
-		self.CR             = 0
-		self.p              = 0
-		self.q              = 0
-		self.kn             = 0
-		self.stabilization  = 0
-
-		#set defaults
-		self.setdefaultparameters()
-
-		#}}}
-	def __repr__(self):
-		# {{{ Display
-		
-		string='   hydrology solution parameters:'
-		string="%s\n%s"%(string,fielddisplay(self,'spcwatercolumn','water thickness constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(self,'n','Manning roughness coefficient'))
-		string="%s\n%s"%(string,fielddisplay(self,'CR','tortuosity parameter'))
-		string="%s\n%s"%(string,fielddisplay(self,'p','dimensionless exponent in Manning velocity formula'))
-		string="%s\n%s"%(string,fielddisplay(self,'q','dimensionless exponent in Manning velocity formula'))
-		string="%s\n%s"%(string,fielddisplay(self,'kn','parameter in effective pressure formula'))
-		string="%s\n%s"%(string,fielddisplay(self,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.'))
-		return string
-		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
-		
-		#Parameters from Johnson's 2002 thesis, section 3.5.4			 
-		self.n=.02			
-		self.CR=.01
-		self.p=2
-		self.q=1
-		self.kn=0
-
-		#Type of stabilization to use 0:nothing 1:artificial_diffusivity
-		self.stabilization=1
-
-		return self
-	#}}}
-
-	def checkconsistency(self,md,solution,analyses):    # {{{
-
-		#Early return
-		if HydrologyAnalysisEnum() not in analyses:
-			return md
-
-		md = checkfield(md,'hydrology.spcwatercolumn','forcing',1)
-		md = checkfield(md,'hydrology.stabilization','>=',0)
-
-		return md
-	# }}}
-
-	def marshall(self,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','n','format','Double')
-		WriteData(fid,'object',self,'fieldname','CR','format','Double')
-		WriteData(fid,'object',self,'fieldname','p','format','Double')
-		WriteData(fid,'object',self,'fieldname','q','format','Double')
-		WriteData(fid,'object',self,'fieldname','kn','format','Double')
-		WriteData(fid,'object',self,'fieldname','stabilization','format','Double')
-	# }}}
-
Index: /issm/trunk/src/m/classes/hydrologydc.m
===================================================================
--- /issm/trunk/src/m/classes/hydrologydc.m	(revision 15396)
+++ /issm/trunk/src/m/classes/hydrologydc.m	(revision 15396)
@@ -0,0 +1,175 @@
+%Hydrologydc class definition
+%
+%   Usage:
+%      hydrologydc=hydrologydc();
+
+classdef hydrologydc
+	properties (SetAccess=public) 
+		water_compressibility    = 0;
+		isefficientlayer         = 0;
+		penalty_factor           = 0;
+		rel_tol                  = 0;
+		sedimentlimit_flag       = 0;
+		sedimentlimit            = 0;
+		transfer_flag            = 0;
+		leakage_factor           = 0;
+
+		spcsediment_head         = NaN;
+		sediment_compressibility = 0;
+		sediment_porosity        = 0;
+		sediment_thickness       = 0;
+		sediment_transmitivity   = 0;
+
+		spcepl_head              = NaN;
+		mask_eplactive           = NaN;
+		epl_compressibility      = 0;
+		epl_porosity             = 0;
+		epl_thickness            = 0;
+		epl_transmitivity        = 0;
+  end
+	methods
+		function obj = hydrologydc(varargin) % {{{ 
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+	    end
+		end 
+		% }}}
+		% {{{ function obj = setdefaultparameters(obj) 
+		function obj = setdefaultparameters(obj) 
+
+		%Parameters from de Fleurian 2013
+			obj.water_compressibility    = 5.04e-10;
+			obj.isefficientlayer         = 1;
+			obj.penalty_factor           = 3;
+			obj.rel_tol                  = 1.0e-06;
+			obj.sedimentlimit_flag       = 0;
+			obj.sedimentlimit            = 0;
+			obj.transfer_flag            = 0;
+			obj.leakage_factor           = 10.0;
+
+			obj.sediment_compressibility = 1.0e-08;
+			obj.sediment_porosity        = 0.4;
+			obj.sediment_thickness       = 20.0;
+			obj.sediment_transmitivity   = 8.0e-04;
+
+			obj.epl_compressibility      = 1.0e-08;
+			obj.epl_porosity             = 0.4;
+			obj.epl_thickness            = 1.0;
+			obj.epl_transmitivity        = 8.0e-02;
+
+		end 
+		% }}}
+		% {{{ function md = checkconsistency(obj,md,solution,analyses) 
+		function md = checkconsistency(obj,md,solution,analyses) 
+		%Early return
+			if ~ismember(HydrologyDCInefficientAnalysisEnum(),analyses) & ~ismember(HydrologyDCEfficientAnalysisEnum(),analyses),
+				return;
+			end
+
+			md = checkfield(md,'hydrology.water_compressibility','>',0,'numel',1);
+			md = checkfield(md,'hydrology.isefficientlayer','numel',[1],'values',[0 1]);
+			md = checkfield(md,'hydrology.penalty_factor','>',0,'numel',1);
+			md = checkfield(md,'hydrology.rel_tol','>',0,'numel',1);
+			md = checkfield(md,'hydrology.sedimentlimit_flag','numel',[1],'values',[0 1 2 3]);
+			md = checkfield(md,'hydrology.transfer_flag','numel',[1],'values',[0 1]);
+			if obj.sedimentlimit_flag==1,
+				md = checkfield(md,'hydrology.sedimentlimit','>',0,'numel',1);
+	    end
+			if obj.transfer_flag==1,
+				md = checkfield(md,'hydrology.leakage_factor','>',0,'numel',1);
+	    end
+
+			md = checkfield(md,'hydrology.spcsediment_head','forcing',1);
+			md = checkfield(md,'hydrology.sediment_compressibility','>',0,'numel',1);
+			md = checkfield(md,'hydrology.sediment_porosity','>',0,'numel',1);
+			md = checkfield(md,'hydrology.sediment_thickness','>',0,'numel',1);
+			md = checkfield(md,'hydrology.sediment_transmitivity','>',0,'numel',1);
+
+			if obj.isefficientlayer==1,
+				md = checkfield(md,'hydrology.spcepl_head','forcing',1);
+				md = checkfield(md,'hydrology.mask_eplactive','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				md = checkfield(md,'hydrology.epl_compressibility','>',0,'numel',1);
+				md = checkfield(md,'hydrology.epl_porosity','>',0,'numel',1);
+				md = checkfield(md,'hydrology.epl_thickness','>',0,'numel',1);
+				md = checkfield(md,'hydrology.epl_transmitivity','>',0,'numel',1);
+	    end
+		end 
+		% }}}
+		% {{{ function disp(obj)
+		function disp(obj) 
+			disp(sprintf('   hydrology Dual Porous Continuum Equivalent parameters:'));
+			disp(sprintf('   - general parameters'));
+			fielddisplay(obj,'water_compressibility','compressibility of water [Pa^-1]');
+			fielddisplay(obj,'isefficientlayer','do we use an efficient drainage system [1: true; 0: false]');
+			fielddisplay(obj,'penalty_factor','exponent of the value used in the penalisation method [dimensionless]');
+			fielddisplay(obj,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]');
+			fielddisplay(obj,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer');
+			disp(sprintf('%55s  0: no limit',' '));
+			disp(sprintf('%55s  1: user defined: %s',' ','sedimentlimit'));
+			disp(sprintf('%55s  2: hydrostatic pressure',' '));
+			disp(sprintf('%55s  3: normal stress',' '));
+			if obj.sedimentlimit_flag==1,
+				fielddisplay(obj,'sedimentlimit','user defined upper limit for the inefficient layer [m]');
+	    end
+			fielddisplay(obj,'transfer_flag',['what kind of transfer method is applied between the layers']);
+			disp(sprintf('%55s  0: no transfer',' '));
+			disp(sprintf('%55s  1: constant leakage factor: %s',' ','leakage_factor'));
+			if obj.transfer_flag==1,
+				fielddisplay(obj,'leakage_factor','user defined leakage factor [m]');
+	    end
+			disp(sprintf('   - for the sediment layer'));
+			fielddisplay(obj,'spcsediment_head','sediment water head constraints (NaN means no constraint) [m above MSL]');
+			fielddisplay(obj,'sediment_compressibility','sediment compressibility [Pa^-1]');
+			fielddisplay(obj,'sediment_porosity','sediment [dimensionless]');
+			fielddisplay(obj,'sediment_thickness','sediment thickness [m]');
+			fielddisplay(obj,'sediment_transmitivity','sediment transmitivity [m^2/s]');
+
+			if obj.isefficientlayer==1,
+				disp(sprintf('   - for the epl layer'));
+				fielddisplay(obj,'spcepl_head','epl water head constraints (NaN means no constraint) [m above MSL]');
+				fielddisplay(obj,'mask_eplactive','active (1) or not (0) EPL');
+				fielddisplay(obj,'epl_compressibility','epl compressibility [Pa^-1]');
+				fielddisplay(obj,'epl_porosity','epl [dimensionless]');
+				fielddisplay(obj,'epl_thickness','epl thickness [m]');
+				fielddisplay(obj,'epl_transmitivity','epl transmitivity [m^2/s]');
+	    end
+
+		end 
+		% }}}
+		% {{{ function marshall(obj,md,fid) 
+		function marshall(obj,md,fid) 
+			WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologydcEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'fieldname','water_compressibility','format','Double');
+			WriteData(fid,'object',obj,'fieldname','isefficientlayer','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',obj,'fieldname','rel_tol','format','Double');
+			WriteData(fid,'object',obj,'fieldname','sedimentlimit_flag','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','transfer_flag','format','Integer');
+			if obj.sedimentlimit_flag==1,
+				WriteData(fid,'object',obj,'fieldname','sedimentlimit','format','Double');
+	    end
+			if obj.transfer_flag==1,
+				WriteData(fid,'object',obj,'fieldname','leakage_factor','format','Double');
+	    end
+
+			WriteData(fid,'object',obj,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','sediment_compressibility','format','Double');			
+			WriteData(fid,'object',obj,'fieldname','sediment_porosity','format','Double');			
+			WriteData(fid,'object',obj,'fieldname','sediment_thickness','format','Double');
+			WriteData(fid,'object',obj,'fieldname','sediment_transmitivity','format','Double');		
+
+			if obj.isefficientlayer==1,	
+				WriteData(fid,'object',obj,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);	
+				WriteData(fid,'object',obj,'fieldname','mask_eplactive','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','epl_compressibility','format','Double');			
+				WriteData(fid,'object',obj,'fieldname','epl_porosity','format','Double');			
+				WriteData(fid,'object',obj,'fieldname','epl_thickness','format','Double');
+				WriteData(fid,'object',obj,'fieldname','epl_transmitivity','format','Double');
+			end
+		end 
+% }}}
+  end
+end
Index: /issm/trunk/src/m/classes/hydrologyshreve.m
===================================================================
--- /issm/trunk/src/m/classes/hydrologyshreve.m	(revision 15396)
+++ /issm/trunk/src/m/classes/hydrologyshreve.m	(revision 15396)
@@ -0,0 +1,72 @@
+%HYDROLOGYSHREVE class definition
+%
+%   Usage:
+%      hydrologyshreve=hydrologyshreve();
+
+classdef hydrologyshreve
+	properties (SetAccess=public) 
+		spcwatercolumn = NaN;
+		n              = 0;
+		CR             = 0;
+		p              = 0;
+		q              = 0;
+		kn             = 0;
+		stabilization  = 0;
+	end
+	methods
+		function obj = hydrologyshreve(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					obj=structtoobj(obj,varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Parameters from Johnson's 2002 thesis, section 3.5.4			 
+			obj.n  = .02;
+			obj.CR = .01;
+			obj.p  = 2;
+			obj.q  = 1;
+			obj.kn = 0;
+
+			%Type of stabilization to use 0:nothing 1:artificial_diffusivity
+			obj.stabilization=1;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(HydrologyShreveAnalysisEnum(),analyses)
+				return;
+			end
+
+			md = checkfield(md,'hydrology.spcwatercolumn','forcing',1);
+			md = checkfield(md,'hydrology.stabilization','>=',0);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   hydrologyshreve solution parameters:'));
+
+			fielddisplay(obj,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]');
+			fielddisplay(obj,'n','Manning roughness coefficient');
+			fielddisplay(obj,'CR','tortuosity parameter');
+			fielddisplay(obj,'p','dimensionless exponent in Manning velocity formula');
+			fielddisplay(obj,'q','dimensionless exponent in Manning velocity formula');
+			fielddisplay(obj,'kn','parameter in effective pressure formula');
+			fielddisplay(obj,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologyshreveEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','n','format','Double');
+			WriteData(fid,'object',obj,'fieldname','CR','format','Double');
+			WriteData(fid,'object',obj,'fieldname','p','format','Double');
+			WriteData(fid,'object',obj,'fieldname','q','format','Double');
+			WriteData(fid,'object',obj,'fieldname','kn','format','Double');
+			WriteData(fid,'object',obj,'fieldname','stabilization','format','Double');
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/hydrologyshreve.py
===================================================================
--- /issm/trunk/src/m/classes/hydrologyshreve.py	(revision 15396)
+++ /issm/trunk/src/m/classes/hydrologyshreve.py	(revision 15396)
@@ -0,0 +1,73 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
+
+class hydrologyshreve(object):
+	"""
+	HYDROLOGYSHREVE class definition
+
+	   Usage:
+	      hydrologyshreve=hydrologyshreve();
+	"""
+
+	def __init__(self): # {{{
+		self.spcwatercolumn = float('NaN')
+		self.n              = 0
+		self.CR             = 0
+		self.p              = 0
+		self.q              = 0
+		self.kn             = 0
+		self.stabilization  = 0
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		
+		string='   hydrologyshreve solution parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'n','Manning roughness coefficient'))
+		string="%s\n%s"%(string,fielddisplay(self,'CR','tortuosity parameter'))
+		string="%s\n%s"%(string,fielddisplay(self,'p','dimensionless exponent in Manning velocity formula'))
+		string="%s\n%s"%(string,fielddisplay(self,'q','dimensionless exponent in Manning velocity formula'))
+		string="%s\n%s"%(string,fielddisplay(self,'kn','parameter in effective pressure formula'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.'))
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#Parameters from Johnson's 2002 thesis, section 3.5.4			 
+		self.n=.02			
+		self.CR=.01
+		self.p=2
+		self.q=1
+		self.kn=0
+
+		#Type of stabilization to use 0:nothing 1:artificial_diffusivity
+		self.stabilization=1
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if HydrologyShreveAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'hydrology.spcwatercolumn','forcing',1)
+		md = checkfield(md,'hydrology.stabilization','>=',0)
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologyshreveEnum(),'format','Integer');
+		WriteData(fid,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','n','format','Double')
+		WriteData(fid,'object',self,'fieldname','CR','format','Double')
+		WriteData(fid,'object',self,'fieldname','p','format','Double')
+		WriteData(fid,'object',self,'fieldname','q','format','Double')
+		WriteData(fid,'object',self,'fieldname','kn','format','Double')
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Double')
+	# }}}
Index: /issm/trunk/src/m/classes/independent.m
===================================================================
--- /issm/trunk/src/m/classes/independent.m	(revision 15395)
+++ /issm/trunk/src/m/classes/independent.m	(revision 15396)
@@ -60,9 +60,12 @@
 			end
 		end % }}}
-		function scalar=typetoscalar(obj) % {{{
+		function scalartype=typetoscalar(obj) % {{{
 			if strcmpi(obj.type,'scalar'),
-				scalar=0;
+				scalartype=0;
 			elseif strcmpi(obj.type,'vertex'),
-				scalar=1;
+				scalartype=1;
+			elseif strcmpi(obj.type,'matrix'),
+				scalartype=1;
+			else error([obj.type ' not supported yet!']);
 			end
 		end % }}}
Index: /issm/trunk/src/m/classes/independent.py
===================================================================
--- /issm/trunk/src/m/classes/independent.py	(revision 15395)
+++ /issm/trunk/src/m/classes/independent.py	(revision 15396)
@@ -30,5 +30,4 @@
 		self=options.AssignObjectFields(self)
 	# }}}
-
 	def __repr__(self):    # {{{
 		s ="   independent variable:\n"
@@ -43,10 +42,8 @@
 		return s
 	# }}}
-
 	def setdefaultparameters(self):    # {{{
 		#do nothing
 		return self
 	# }}}
-
 	def checkconsistency(self,md,i,solution,analyses,driver):    # {{{
 		if not numpy.isnan(self.fos_forward_index):
@@ -65,5 +62,4 @@
 		return md
 	# }}}
-
 	def typetoscalar(self):    # {{{
 		if   strcmpi(self.type,'scalar'):
@@ -74,3 +70,2 @@
 		return scalar
 	# }}}
-
Index: /issm/trunk/src/m/classes/initialization.m
===================================================================
--- /issm/trunk/src/m/classes/initialization.m	(revision 15395)
+++ /issm/trunk/src/m/classes/initialization.m	(revision 15396)
@@ -12,8 +12,8 @@
 		pressure      = NaN;
 		temperature   = NaN;
-		surfacetemp   = NaN;
-		basaltemp     = NaN;
+		waterfraction = NaN;
+		sediment_head = NaN;
+		epl_head      = NaN;
 		watercolumn   = NaN;
-		waterfraction = NaN;
 	end
 	methods
@@ -40,8 +40,5 @@
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if ismember(HydrologyAnalysisEnum(),analyses),
-				md = checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices 1]);
-			end
-			if ismember(BalancethicknessAnalysisEnum(),analyses),
+			if ismember(BalancethicknessAnalysisEnum(),analyses) & solution==BalancethicknessSolutionEnum,
 				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -60,28 +57,50 @@
 				md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices 1]);
 			end
+			if ismember(HydrologyShreveAnalysisEnum(),analyses),
+				if isa(md.hydrology,'hydrologyshreve'),
+					md = checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				end
+			end
+			if ismember(HydrologyDCInefficientAnalysisEnum(),analyses),
+				if isa(md.hydrology,'hydrologydc'),
+					md = checkfield(md,'initialization.sediment_head','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				end
+			end
+			if ismember(HydrologyDCEfficientAnalysisEnum(),analyses),
+				if isa(md.hydrology,'hydrologydc'),
+					if md.hydrology.isefficientlayer==1,
+						md = checkfield(md,'initialization.epl_head','NaN',1,'size',[md.mesh.numberofvertices 1]);
+					end
+				end
+			end
 		end % }}}
 		function disp(obj) % {{{
 			disp(sprintf('   initial field values:'));
 
-			fielddisplay(obj,'vx','x component of velocity');
-			fielddisplay(obj,'vy','y component of velocity');
-			fielddisplay(obj,'vz','z component of velocity');
-			fielddisplay(obj,'vel','velocity norm');
-			fielddisplay(obj,'pressure','pressure field');
-			fielddisplay(obj,'temperature','temperature in Kelvins');
-			fielddisplay(obj,'surfacetemp','surface temperature in Kelvins');
-			fielddisplay(obj,'basaltemp','basal temperature in Kelvins');
-			fielddisplay(obj,'watercolumn','thickness of subglacial water');
+			fielddisplay(obj,'vx','x component of velocity [m/yr]');
+			fielddisplay(obj,'vy','y component of velocity [m/yr]');
+			fielddisplay(obj,'vz','z component of velocity [m/yr]');
+			fielddisplay(obj,'vel','velocity norm [m/yr]');
+			fielddisplay(obj,'pressure','pressure field [Pa]');
+			fielddisplay(obj,'temperature','temperature [K]');
 			fielddisplay(obj,'waterfraction','fraction of water in the ice');
+			fielddisplay(obj,'sediment_head','sediment water head of subglacial system [m]');
+			fielddisplay(obj,'epl_head','epl water head of subglacial system [m]');
+			fielddisplay(obj,'watercolumn','thickness of subglacial water [m]');
 
 		end % }}}
-		function marshall(obj,fid) % {{{
-			WriteData(fid,'data',obj.vx,'format','DoubleMat','mattype',1,'enum',VxEnum);
-			WriteData(fid,'data',obj.vy,'format','DoubleMat','mattype',1,'enum',VyEnum);
-			WriteData(fid,'data',obj.vz,'format','DoubleMat','mattype',1,'enum',VzEnum);
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'data',obj.vx,'format','DoubleMat','mattype',1,'enum',VxEnum,'scale',1./yts);
+			WriteData(fid,'data',obj.vy,'format','DoubleMat','mattype',1,'enum',VyEnum,'scale',1./yts);
+			WriteData(fid,'data',obj.vz,'format','DoubleMat','mattype',1,'enum',VzEnum,'scale',1./yts);
 			WriteData(fid,'data',obj.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum);
 			WriteData(fid,'data',obj.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum);
+			WriteData(fid,'data',obj.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum);
+			WriteData(fid,'data',obj.sediment_head,'format','DoubleMat','mattype',1,'enum',SedimentHeadEnum);
+			WriteData(fid,'data',obj.epl_head,'format','DoubleMat','mattype',1,'enum',EplHeadEnum);
 			WriteData(fid,'data',obj.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum);
-			WriteData(fid,'data',obj.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/initialization.py
===================================================================
--- /issm/trunk/src/m/classes/initialization.py	(revision 15395)
+++ /issm/trunk/src/m/classes/initialization.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 from fielddisplay import fielddisplay
@@ -14,7 +13,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		
 		self.vx            = float('NaN')
@@ -24,8 +21,7 @@
 		self.pressure      = float('NaN')
 		self.temperature   = float('NaN')
-		self.surfacetemp   = float('NaN')
-		self.basaltemp     = float('NaN')
+		self.waterfraction = float('NaN')
 		self.watercolumn   = float('NaN')
-		self.waterfraction = float('NaN')
+		self.sediment_head  = float('NaN')
 
 		#set defaults
@@ -33,27 +29,22 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string='   initial field values:'
 
-		string="%s\n%s"%(string,fielddisplay(self,'vx','x component of velocity'))
-		string="%s\n%s"%(string,fielddisplay(self,'vy','y component of velocity'))
-		string="%s\n%s"%(string,fielddisplay(self,'vz','z component of velocity'))
-		string="%s\n%s"%(string,fielddisplay(self,'vel','velocity norm'))
-		string="%s\n%s"%(string,fielddisplay(self,'pressure','pressure field'))
-		string="%s\n%s"%(string,fielddisplay(self,'temperature','temperature in Kelvins'))
-		string="%s\n%s"%(string,fielddisplay(self,'surfacetemp','surface temperature in Kelvins'))
-		string="%s\n%s"%(string,fielddisplay(self,'basaltemp','basal temperature in Kelvins'))
-		string="%s\n%s"%(string,fielddisplay(self,'watercolumn','thickness of subglacial water'))
+		string="%s\n%s"%(string,fielddisplay(self,'vx','x component of velocity [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vy','y component of velocity [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vz','z component of velocity [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vel','velocity norm [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'pressure','pressure [Pa]'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperature','temperature [K]'))
 		string="%s\n%s"%(string,fielddisplay(self,'waterfraction','fraction of water in the ice'))
+		string="%s\n%s"%(string,fielddisplay(self,'watercolumn','thickness of subglacial water [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'sediment_head','sediment water head of subglacial system [m]'))
 
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		if DiagnosticHorizAnalysisEnum() in analyses:
@@ -64,6 +55,4 @@
 			md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
 			md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
-		if HydrologyAnalysisEnum() in analyses:
-			md = checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices])
 		if BalancethicknessAnalysisEnum() in analyses:
 			md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
@@ -80,16 +69,19 @@
 		if (EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy) or solution==EnthalpySolutionEnum():
 			md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices])
-
+		if HydrologyShreveAnalysisEnum() in analyses:
+			md = checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices])
 		return md
 	# }}}
+	def marshall(self,md,fid):    # {{{
 
-	def marshall(self,fid):    # {{{
-		WriteData(fid,'data',self.vx,'format','DoubleMat','mattype',1,'enum',VxEnum())
-		WriteData(fid,'data',self.vy,'format','DoubleMat','mattype',1,'enum',VyEnum())
-		WriteData(fid,'data',self.vz,'format','DoubleMat','mattype',1,'enum',VzEnum())
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'data',self.vx,'format','DoubleMat','mattype',1,'enum',VxEnum(),'scale',1./yts)
+		WriteData(fid,'data',self.vy,'format','DoubleMat','mattype',1,'enum',VyEnum(),'scale',1./yts)
+		WriteData(fid,'data',self.vz,'format','DoubleMat','mattype',1,'enum',VzEnum(),'scale',1./yts)
 		WriteData(fid,'data',self.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum())
 		WriteData(fid,'data',self.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum())
+		WriteData(fid,'data',self.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum())
 		WriteData(fid,'data',self.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum())
-		WriteData(fid,'data',self.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum())
+		WriteData(fid,'data',self.sediment_head,'format','DoubleMat','mattype',1,'enum',SedimentHeadEnum())
 	# }}}
-
Index: /issm/trunk/src/m/classes/inversion.m
===================================================================
--- /issm/trunk/src/m/classes/inversion.m	(revision 15395)
+++ /issm/trunk/src/m/classes/inversion.m	(revision 15396)
@@ -124,5 +124,5 @@
 			if solution==BalancethicknessSolutionEnum()
 				md = checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
-			elseif solution==WeakBalancethicknessSolutionEnum()
+			elseif solution==BalancethicknessSoftSolutionEnum()
 				md = checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
 			else
@@ -134,6 +134,6 @@
 			disp(sprintf('   inversion parameters:'));
 			fielddisplay(obj,'iscontrol','is inversion activated?');
-			fielddisplay(obj,'incomplete_adjoint','do we assume linear viscosity?');
-			fielddisplay(obj,'control_parameters','parameter where inverse control is carried out; ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
 			fielddisplay(obj,'nsteps','number of optimization searches');
 			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
@@ -146,7 +146,7 @@
 			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
 			fielddisplay(obj,'gradient_only','stop control method solution at gradient');
-			fielddisplay(obj,'vx_obs','observed velocity x component [m/a]');
-			fielddisplay(obj,'vy_obs','observed velocity y component [m/a]');
-			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/a]');
+			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
 			fielddisplay(obj,'thickness_obs','observed thickness [m]');
 			disp('Available cost functions:');
@@ -161,5 +161,7 @@
 			disp('   503: ThicknessAbsGradient');
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
 
 			WriteData(fid,'object',obj,'fieldname','iscontrol','format','Boolean');
@@ -176,7 +178,7 @@
 			WriteData(fid,'object',obj,'fieldname','step_threshold','format','DoubleMat','mattype',3);
 			WriteData(fid,'object',obj,'fieldname','gradient_only','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','vx_obs','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','vy_obs','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','vz_obs','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',obj,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
 			WriteData(fid,'object',obj,'fieldname','thickness_obs','format','DoubleMat','mattype',1);
 
Index: /issm/trunk/src/m/classes/inversion.py
===================================================================
--- /issm/trunk/src/m/classes/inversion.py	(revision 15395)
+++ /issm/trunk/src/m/classes/inversion.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 import copy
@@ -16,7 +15,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.iscontrol                   = 0
 		self.tao                         = 0
@@ -43,10 +40,9 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string='   inversion parameters:'
 		string="%s\n%s"%(string,fielddisplay(self,'iscontrol','is inversion activated?'))
-		string="%s\n%s"%(string,fielddisplay(self,'incomplete_adjoint','do we assume linear viscosity?'))
-		string="%s\n%s"%(string,fielddisplay(self,'control_parameters','parameter where inverse control is carried out; ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}'))
+		string="%s\n%s"%(string,fielddisplay(self,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity'))
+		string="%s\n%s"%(string,fielddisplay(self,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}'))
 		string="%s\n%s"%(string,fielddisplay(self,'nsteps','number of optimization searches'))
 		string="%s\n%s"%(string,fielddisplay(self,'cost_functions','indicate the type of response for each optimization step'))
@@ -59,7 +55,7 @@
 		string="%s\n%s"%(string,fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex'))
 		string="%s\n%s"%(string,fielddisplay(self,'gradient_only','stop control method solution at gradient'))
-		string="%s\n%s"%(string,fielddisplay(self,'vx_obs','observed velocity x component [m/a]'))
-		string="%s\n%s"%(string,fielddisplay(self,'vy_obs','observed velocity y component [m/a]'))
-		string="%s\n%s"%(string,fielddisplay(self,'vel_obs','observed velocity magnitude [m/a]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vx_obs','observed velocity x component [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vy_obs','observed velocity y component [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]'))
 		string="%s\n%s"%(string,fielddisplay(self,'thickness_obs','observed thickness [m]'))
 		string="%s\n%s"%(string,'Available cost functions:')
@@ -75,5 +71,4 @@
 		return string
 		#}}}
-
 	def setdefaultparameters(self): # {{{
 		
@@ -117,5 +112,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -149,6 +143,7 @@
 		return md
 	# }}}
+	def marshall(self,md,fid):    # {{{
 
-	def marshall(self,fid):    # {{{
+		yts=365.0*24.0*3600.0
 
 		WriteData(fid,'object',self,'fieldname','iscontrol','format','Boolean')
@@ -166,7 +161,7 @@
 		WriteData(fid,'object',self,'fieldname','step_threshold','format','DoubleMat','mattype',3)
 		WriteData(fid,'object',self,'fieldname','gradient_only','format','Boolean')
-		WriteData(fid,'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
 		WriteData(fid,'object',self,'fieldname','thickness_obs','format','DoubleMat','mattype',1)
 
@@ -194,3 +189,2 @@
 		WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
 	# }}}
-
Index: /issm/trunk/src/m/classes/mask.m
===================================================================
--- /issm/trunk/src/m/classes/mask.m	(revision 15395)
+++ /issm/trunk/src/m/classes/mask.m	(revision 15396)
@@ -47,5 +47,5 @@
 			fielddisplay(obj,'vertexonrock','vertex on rock flags list');
 		end % }}}
-		function marshall(obj,fid) % {{{
+		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);
Index: /issm/trunk/src/m/classes/mask.py
===================================================================
--- /issm/trunk/src/m/classes/mask.py	(revision 15395)
+++ /issm/trunk/src/m/classes/mask.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -13,7 +12,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.elementonfloatingice = float('NaN')
 		self.elementongroundedice = float('NaN')
@@ -27,6 +24,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string="   masks:"
 
@@ -39,10 +35,7 @@
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -56,6 +49,5 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	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)
@@ -65,3 +57,2 @@
 		WriteData(fid,'object',self,'fieldname','vertexonwater','format','DoubleMat','mattype',1)
 	# }}}
-
Index: /issm/trunk/src/m/classes/matdamageice.m
===================================================================
--- /issm/trunk/src/m/classes/matdamageice.m	(revision 15395)
+++ /issm/trunk/src/m/classes/matdamageice.m	(revision 15396)
@@ -21,4 +21,11 @@
 		rheology_Z   = NaN;
 		rheology_law = '';
+
+		%gia: 
+		lithosphere_shear_modulus  = 0.;
+		lithosphere_density        = 0.;
+		mantle_shear_modulus       = 0.;
+		mantle_density             = 0.;
+
 	end
 	methods
@@ -79,4 +86,11 @@
 			%available: none, paterson and arrhenius
 			obj.rheology_law='Paterson';
+
+			%GIA: 
+			obj.lithosphere_shear_modulus  = 6.7*10^10;  % (Pa)
+			obj.lithosphere_density        = 3.32;       % (g/cm^-3)
+			obj.mantle_shear_modulus       = 1.45*10^11; % (Pa)
+			obj.mantle_density             = 3.34;       % (g/cm^-3)
+
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -89,4 +103,12 @@
 			md = checkfield(md,'materials.rheology_Z','>',0,'size',[md.mesh.numberofvertices 1]);
 			md = checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius'});
+
+			if ismember(GiaAnalysisEnum(),analyses),
+				md = checkfield(md,'materials.lithosphere_shear_modulus','>',0,'numel',1);
+				md = checkfield(md,'materials.lithosphere_density','>',0,'numel',1);
+				md = checkfield(md,'materials.mantle_shear_modulus','>',0,'numel',1);
+				md = checkfield(md,'materials.mantle_density','>',0,'numel',1);
+			end
+
 		end % }}}
 		function disp(obj) % {{{
@@ -108,6 +130,11 @@
 			fielddisplay(obj,'rheology_Z','rheology multiplier');
 			fielddisplay(obj,'rheology_law','law for the temperature dependance of the rheology: ''None'', ''Paterson'' or ''Arrhenius''');
+			fielddisplay(obj,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
+			fielddisplay(obj,'lithosphere_density','Lithosphere density [g/cm^-3]');
+			fielddisplay(obj,'mantle_shear_modulus','Mantle shear modulus [Pa]');
+			fielddisplay(obj,'mantle_density','Mantle density [g/cm^-3]');
+
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'enum',MaterialsEnum(),'data',MatdamageiceEnum(),'format','Integer');
 			WriteData(fid,'object',obj,'class','materials','fieldname','rho_ice','format','Double');
@@ -126,4 +153,10 @@
 			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_Z','format','DoubleMat','mattype',1);
 			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
+
+			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3);
+			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_density','format','Double','scale',10^3);
+
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/matdamageice.py
===================================================================
--- /issm/trunk/src/m/classes/matdamageice.py	(revision 15395)
+++ /issm/trunk/src/m/classes/matdamageice.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -31,4 +30,10 @@
 		self.rheology_law = ''
 
+		#gia: 
+		self.lithosphere_shear_modulus  = 0.
+		self.lithosphere_density        = 0.
+		self.mantle_shear_modulus       = 0.
+		self.mantle_density             = 0.
+
 		if not len(args):
 			self.setdefaultparameters()
@@ -37,5 +42,29 @@
 
 	# }}}
+	def __repr__(self):    # {{{
+		s ='   Materials:\n'
 
+		s+="%s\n" % fielddisplay(self,"rho_ice","ice density [kg/m^3]")
+		s+="%s\n" % fielddisplay(self,"rho_water","ocean water density [kg/m^3]")
+		s+="%s\n" % fielddisplay(self,"rho_freshwater","fresh water density [kg/m^3]")
+		s+="%s\n" % fielddisplay(self,"mu_water","water viscosity [N s/m^2]")
+		s+="%s\n" % fielddisplay(self,"heatcapacity","heat capacity [J/kg/K]")
+		s+="%s\n" % fielddisplay(self,"thermalconductivity","ice thermal conductivity [W/m/K]")
+		s+="%s\n" % fielddisplay(self,"meltingpoint","melting point of ice at 1atm in K")
+		s+="%s\n" % fielddisplay(self,"latentheat","latent heat of fusion [J/m^3]")
+		s+="%s\n" % fielddisplay(self,"beta","rate of change of melting point with pressure [K/Pa]")
+		s+="%s\n" % fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]")
+		s+="%s\n" % fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]")
+		s+="%s\n" % fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]")
+		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,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]")
+		s+="%s\n" % fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]")
+		s+="%s\n" % fielddisplay(self,"mantle_shear_modulus","Mantle shear modulus [Pa]")
+		s+="%s\n" % fielddisplay(self,"mantle_density","Mantle density [g/cm^-3]")
+
+		return s
+	# }}}
 	def setdefaultparameters(self):    # {{{
 
@@ -76,6 +105,11 @@
 		#available: none, paterson and arrhenius
 		self.rheology_law='Paterson'
+
+		# GIA:
+		self.lithosphere_shear_modulus  = 6.7*10**10;  # (Pa)
+		self.lithosphere_density        = 3.32;       # (g/cm^-3)
+		self.mantle_shear_modulus       = 1.45*10**11; # (Pa)
+		self.mantle_density             = 3.34;       # (g/cm^-3)
 	# }}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		md = checkfield(md,'materials.rho_ice','>',0)
@@ -87,31 +121,12 @@
 		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.lithosphere_shear_modulus','>',0,'numel',[1]);
+		md = checkfield(md,'materials.lithosphere_density','>',0,'numel',[1]);
+		md = checkfield(md,'materials.mantle_shear_modulus','>',0,'numel',[1]);
+		md = checkfield(md,'materials.mantle_density','>',0,'numel',[1]);
 
 		return md
 	# }}}
-
-	def __repr__(self):    # {{{
-		s ='   Materials:\n'
-
-		s+="%s\n" % fielddisplay(self,"rho_ice","ice density [kg/m^3]")
-		s+="%s\n" % fielddisplay(self,"rho_water","ocean water density [kg/m^3]")
-		s+="%s\n" % fielddisplay(self,"rho_freshwater","fresh water density [kg/m^3]")
-		s+="%s\n" % fielddisplay(self,"mu_water","water viscosity [N s/m^2]")
-		s+="%s\n" % fielddisplay(self,"heatcapacity","heat capacity [J/kg/K]")
-		s+="%s\n" % fielddisplay(self,"thermalconductivity","ice thermal conductivity [W/m/K]")
-		s+="%s\n" % fielddisplay(self,"meltingpoint","melting point of ice at 1atm in K")
-		s+="%s\n" % fielddisplay(self,"latentheat","latent heat of fusion [J/m^3]")
-		s+="%s\n" % fielddisplay(self,"beta","rate of change of melting point with pressure [K/Pa]")
-		s+="%s\n" % fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]")
-		s+="%s\n" % fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]")
-		s+="%s\n" % fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]")
-		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'")
-
-		return s
-	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'enum',MaterialsEnum(),'data',MatdamageiceEnum(),'format','Integer')
 		WriteData(fid,'object',self,'class','materials','fieldname','rho_ice','format','Double')
@@ -130,4 +145,8 @@
 		WriteData(fid,'object',self,'class','materials','fieldname','rheology_Z','format','DoubleMat','mattype',1)
 		WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')
+
+		WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+		WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.);
+		WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+		WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.);
 	# }}}
-
Index: /issm/trunk/src/m/classes/matice.m
===================================================================
--- /issm/trunk/src/m/classes/matice.m	(revision 15395)
+++ /issm/trunk/src/m/classes/matice.m	(revision 15396)
@@ -20,4 +20,11 @@
 		rheology_n   = NaN;
 		rheology_law = '';
+
+		%gia: 
+		lithosphere_shear_modulus  = 0.;
+		lithosphere_density        = 0.;
+		mantle_shear_modulus       = 0.;
+		mantle_density             = 0.;
+
 	end
 	methods
@@ -78,4 +85,11 @@
 			%available: none, paterson and arrhenius
 			obj.rheology_law='Paterson';
+
+			% GIA:
+			obj.lithosphere_shear_modulus  = 6.7*10^10;  % (Pa)
+			obj.lithosphere_density        = 3.32;       % (g/cm^-3)
+			obj.mantle_shear_modulus       = 1.45*10^11; % (Pa)
+			obj.mantle_density             = 3.34;       % (g/cm^-3)
+
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -87,4 +101,12 @@
 			md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements 1]);
 			md = checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius'});
+
+			if ismember(GiaAnalysisEnum(),analyses),
+				md = checkfield(md,'materials.lithosphere_shear_modulus','>',0,'numel',1);
+				md = checkfield(md,'materials.lithosphere_density','>',0,'numel',1);
+				md = checkfield(md,'materials.mantle_shear_modulus','>',0,'numel',1);
+				md = checkfield(md,'materials.mantle_density','>',0,'numel',1);
+			end
+
 		end % }}}
 		function disp(obj) % {{{
@@ -105,6 +127,10 @@
 			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,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
+			fielddisplay(obj,'lithosphere_density','Lithosphere density [g/cm^-3]');
+			fielddisplay(obj,'mantle_shear_modulus','Mantle shear modulus [Pa]');
+			fielddisplay(obj,'mantle_density','Mantle density [g/cm^-3]');
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'enum',MaterialsEnum(),'data',MaticeEnum(),'format','Integer');
 			WriteData(fid,'object',obj,'class','materials','fieldname','rho_ice','format','Double');
@@ -122,4 +148,9 @@
 			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
 			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
+
+			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3);
+			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_density','format','Double','scale',10^3);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/matice.py
===================================================================
--- /issm/trunk/src/m/classes/matice.py	(revision 15395)
+++ /issm/trunk/src/m/classes/matice.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -14,26 +13,29 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
-		self.rho_ice                    = 0.
-		self.rho_water                  = 0.
-		self.rho_freshwater             = 0.
-		self.mu_water                   = 0.
-		self.heatcapacity               = 0.
-		self.latentheat                 = 0.
-		self.thermalconductivity        = 0.
-		self.meltingpoint               = 0.
-		self.beta                       = 0.
-		self.mixed_layer_capacity       = 0.
-		self.thermal_exchange_velocity  = 0.
-		self.rheology_B   = float('NaN')
-		self.rheology_n   = float('NaN')
-		self.rheology_law = ''
+	def __init__(self): # {{{
+		self.rho_ice                   = 0.
+		self.rho_water                 = 0.
+		self.rho_freshwater            = 0.
+		self.mu_water                  = 0.
+		self.heatcapacity              = 0.
+		self.latentheat                = 0.
+		self.thermalconductivity       = 0.
+		self.meltingpoint              = 0.
+		self.beta                      = 0.
+		self.mixed_layer_capacity      = 0.
+		self.thermal_exchange_velocity = 0.
+		self.rheology_B                = float('NaN')
+		self.rheology_n                = float('NaN')
+		self.rheology_law              = ''
+
+		#gia: 
+		self.lithosphere_shear_modulus  = 0.
+		self.lithosphere_density        = 0.
+		self.mantle_shear_modulus       = 0.
+		self.mantle_density             = 0.
 
 		self.setdefaultparameters()
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string="   Materials:"
 
@@ -52,9 +54,12 @@
 		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,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mantle_shear_modulus","Mantle shear modulus [Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mantle_density","Mantle density [g/cm^-3]"))
 
 		return string
 		#}}}
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		#ice density (kg/m^3)
 		self.rho_ice=917.
@@ -93,7 +98,13 @@
 		#available: none, paterson and arrhenius
 		self.rheology_law='Paterson'
+
+		# GIA:
+		self.lithosphere_shear_modulus  = 6.7*10**10  # (Pa)
+		self.lithosphere_density        = 3.32        # (g/cm^-3)
+		self.mantle_shear_modulus       = 1.45*10**11 # (Pa)
+		self.mantle_density             = 3.34        # (g/cm^-3)
+
 		return self
 		#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		md = checkfield(md,'materials.rho_ice','>',0)
@@ -104,8 +115,11 @@
 		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.lithosphere_shear_modulus','>',0,'numel',[1]);
+		md = checkfield(md,'materials.lithosphere_density','>',0,'numel',[1]);
+		md = checkfield(md,'materials.mantle_shear_modulus','>',0,'numel',[1]);
+		md = checkfield(md,'materials.mantle_density','>',0,'numel',[1]);
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'enum',MaterialsEnum(),'data',MaticeEnum(),'format','Integer');
 		WriteData(fid,'object',self,'class','materials','fieldname','rho_ice','format','Double')
@@ -123,4 +137,8 @@
 		WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
 		WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')
+
+		WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+		WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.);
+		WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+		WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.);
 	# }}}
-
Index: /issm/trunk/src/m/classes/mesh.m
===================================================================
--- /issm/trunk/src/m/classes/mesh.m	(revision 15395)
+++ /issm/trunk/src/m/classes/mesh.m	(revision 15396)
@@ -45,4 +45,17 @@
 		extractedvertices           = NaN
 		extractedelements           = NaN
+	end
+	methods (Static)
+		function obj = loadobj(obj) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. Update old properties here
+
+			%2012 June 28th
+			if numel(obj.edges)>1 & any(isnan(obj.edges(:)))
+				disp('Update model edges from previous version');
+				obj.edges(isnan(obj.edges))=-1;
+			end
+
+		end% }}}
 	end
 	methods
@@ -129,7 +142,7 @@
 				fielddisplay(obj,'numberofelements2d','number of elements');
 				fielddisplay(obj,'numberofvertices2d','number of vertices');
-				fielddisplay(obj,'elements2d','index into (x,y,z), coordinates of the vertices');
-				fielddisplay(obj,'x2d','vertices x coordinate');
-				fielddisplay(obj,'y2d','vertices y coordinate');
+				fielddisplay(obj,'elements2d','vertex indices of the mesh elements');
+				fielddisplay(obj,'x2d','vertices x coordinate [m]');
+				fielddisplay(obj,'y2d','vertices y coordinate [m]');
 
 				disp(sprintf('\n      Elements and vertices of the extruded 3d mesh:'));
@@ -139,13 +152,13 @@
 			fielddisplay(obj,'numberofelements','number of elements');
 			fielddisplay(obj,'numberofvertices','number of vertices');
-			fielddisplay(obj,'elements','index into (x,y,z), coordinates of the vertices');
-			fielddisplay(obj,'x','vertices x coordinate');
-			fielddisplay(obj,'y','vertices y coordinate');
-			fielddisplay(obj,'z','vertices z coordinate');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'z','vertices z coordinate [m]');
 			fielddisplay(obj,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
 			fielddisplay(obj,'numberofedges','number of edges of the 2d mesh');
 
 			disp(sprintf('\n      Properties:'));
-			fielddisplay(obj,'dimension','mesh dimension (2d or 3d)');
+			fielddisplay(obj,'dimension','mesh dimension');
 			fielddisplay(obj,'numberoflayers','number of extrusion layers');
 			fielddisplay(obj,'vertexonbed','lower vertices flags list');
@@ -170,9 +183,9 @@
 
 			disp(sprintf('\n      Projection:'));
-			fielddisplay(obj,'lat','vertices latitude');
-			fielddisplay(obj,'long','vertices longitude');
+			fielddisplay(obj,'lat','vertices latitude [degrees]');
+			fielddisplay(obj,'long','vertices longitude [degrees]');
 			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','x','format','DoubleMat','mattype',1);
 			WriteData(fid,'object',obj,'fieldname','y','format','DoubleMat','mattype',1);
Index: /issm/trunk/src/m/classes/mesh.py
===================================================================
--- /issm/trunk/src/m/classes/mesh.py	(revision 15395)
+++ /issm/trunk/src/m/classes/mesh.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 from fielddisplay import fielddisplay
@@ -14,7 +13,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.x                           = float('NaN');
 		self.y                           = float('NaN');
@@ -61,6 +58,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string="   Mesh:" 
 
@@ -71,7 +67,7 @@
 			string="%s\n%s"%(string,fielddisplay(self,"numberofelements2d","number of elements"))
 			string="%s\n%s"%(string,fielddisplay(self,"numberofvertices2d","number of vertices"))
-			string="%s\n%s"%(string,fielddisplay(self,"elements2d","index into (x,y,z), coordinates of the vertices"))
-			string="%s\n%s"%(string,fielddisplay(self,"x2d","vertices x coordinate"))
-			string="%s\n%s"%(string,fielddisplay(self,"y2d","vertices y coordinate"))
+			string="%s\n%s"%(string,fielddisplay(self,"elements2d","vertex indices of the mesh elements"))
+			string="%s\n%s"%(string,fielddisplay(self,"x2d","vertices x coordinate [m]"))
+			string="%s\n%s"%(string,fielddisplay(self,"y2d","vertices y coordinate [m]"))
 
 			string="%s\n%s"%(string,"\n\n      Elements and vertices of the extruded 3d mesh:")
@@ -80,8 +76,8 @@
 		string="%s\n%s"%(string,fielddisplay(self,"numberofelements","number of elements"))
 		string="%s\n%s"%(string,fielddisplay(self,"numberofvertices","number of vertices"))
-		string="%s\n%s"%(string,fielddisplay(self,"elements","index into (x,y,z), coordinates of the vertices"))
-		string="%s\n%s"%(string,fielddisplay(self,"x","vertices x coordinate"))
-		string="%s\n%s"%(string,fielddisplay(self,"y","vertices y coordinate"))
-		string="%s\n%s"%(string,fielddisplay(self,"z","vertices z coordinate"))
+		string="%s\n%s"%(string,fielddisplay(self,"elements","vertex indices of the mesh elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"x","vertices x coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"y","vertices y coordinate [m]"))
+		string="%s\n%s"%(string,fielddisplay(self,"z","vertices z coordinate [m]"))
 		string="%s\n%s"%(string,fielddisplay(self,"edges","edges of the 2d mesh (vertex1 vertex2 element1 element2)"))
 		string="%s\n%s"%(string,fielddisplay(self,"numberofedges","number of edges of the 2d mesh"))
@@ -110,12 +106,10 @@
 
 		string="%s%s"%(string,"\n\n      Projection:")
-		string="%s\n%s"%(string,fielddisplay(self,"lat","vertices latitude"))
-		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude"))
+		string="%s\n%s"%(string,fielddisplay(self,"lat","vertices latitude [degrees]"))
+		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
 		string="%s\n%s"%(string,fielddisplay(self,"hemisphere","Indicate hemisphere 'n' or 's'"))
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#the connectivity is the averaged number of nodes linked to a
@@ -128,5 +122,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -177,6 +170,5 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','x','format','DoubleMat','mattype',1)
 		WriteData(fid,'object',self,'fieldname','y','format','DoubleMat','mattype',1)
@@ -201,3 +193,2 @@
 		WriteData(fid,'object',self,'fieldname','numberofelements2d','format','Integer')
 	# }}}
-
Index: /issm/trunk/src/m/classes/miscellaneous.m
===================================================================
--- /issm/trunk/src/m/classes/miscellaneous.m	(revision 15395)
+++ /issm/trunk/src/m/classes/miscellaneous.m	(revision 15396)
@@ -35,5 +35,5 @@
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','name','format','String');
 		end % }}}
Index: /issm/trunk/src/m/classes/miscellaneous.py
===================================================================
--- /issm/trunk/src/m/classes/miscellaneous.py	(revision 15395)
+++ /issm/trunk/src/m/classes/miscellaneous.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from collections import OrderedDict
 from fielddisplay import fielddisplay
@@ -14,7 +13,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.notes = ''
 		self.name  = ''
@@ -25,6 +22,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string='   miscellaneous parameters:'
 
@@ -34,17 +30,12 @@
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		md = checkfield(md,'miscellaneous.name','empty',1)
 		return md
 	# }}}
-
-	def marshall(self,fid):    #  {{{
+	def marshall(self,md,fid):    #  {{{
 		WriteData(fid,'object',self,'fieldname','name','format','String')
 	# }}}
-
Index: /issm/trunk/src/m/classes/model/model.m
===================================================================
--- /issm/trunk/src/m/classes/model/model.m	(revision 15395)
+++ /issm/trunk/src/m/classes/model/model.m	(revision 15396)
@@ -25,5 +25,5 @@
 		verbose          = 0;
 		settings         = 0;
-		solver           = 0;
+		toolkits         = 0;
 		cluster          = 0;
 
@@ -36,4 +36,5 @@
 		steadystate      = 0;
 		transient        = 0;
+		gia              = 0;
 
 		autodiff         = 0;
@@ -82,8 +83,12 @@
 				end
 			end
-			%2012 June 28th
-			if sum(sum(isnan(md.mesh.edges)))>0
-				disp('Update model edges from previous version');
-				md.mesh.edges(isnan(md.mesh.edges))=-1;
+			%2013 April 12
+			if numel(md.diagnostic.loadingforce==1)
+				md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
+			end
+			%2013 April 17
+			if isa(md.hydrology,'hydrology'),
+				disp('Recovering old hydrology class');
+				md.hydrology=hydrologyshreve(md.materials);
 			end
 
@@ -152,4 +157,8 @@
 			if ~isnan(md.initialization.temperature),md.initialization.temperature=DepthAverage(md,md.initialization.temperature);end;
 
+			%gia
+			if ~isnan(md.gia.mantle_viscosity), md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1); end
+			if ~isnan(md.gia.lithosphere_thickness), md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1); end
+
 			%bedinfo and surface info
 			md.mesh.elementonbed=ones(md.mesh.numberofelements2d,1);
@@ -172,4 +181,5 @@
 			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.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
@@ -212,5 +222,5 @@
 			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.vertexonrock=project2d(md,md.mask.vertexonrock,1);
 
 			%lat long
@@ -718,4 +728,5 @@
 			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]
@@ -746,4 +757,6 @@
 			md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node');
 			md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node');
+			md.gia.mantle_viscosity=project3d(md,'vector',md.gia.mantle_viscosity,'type','node');
+			md.gia.lithosphere_thickness=project3d(md,'vector',md.gia.lithosphere_thickness,'type','node');
 			md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node');
 			md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node');
@@ -810,5 +823,5 @@
 			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.solver=structmd.petscoptions; end
+			if isfield(structmd,'petscoptions') & ~isempty(structmd.petscoptions), md.toolkits=structmd.petscoptions; end
 			if isfield(structmd,'g'), md.constants.g=structmd.g; end
 			if isfield(structmd,'yts'), md.constants.yts=structmd.yts; end
@@ -976,8 +989,10 @@
 				pos=find(~isnan(structmd.spcvz)); md.diagnostic.spcvz(pos)=structmd.spcvz(pos);     
 			end
-			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;
+			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;
+				end
 			end
 			if isfield(structmd,'elements_type') & structmd.elements_type(end,end)>50,
@@ -1055,4 +1070,7 @@
 			end
 
+			if ~isfield(structmd,'loadingforce');
+				md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
+			end
 		end% }}}
 		function md = setdefaultparameters(md) % {{{
@@ -1073,20 +1091,16 @@
 			md.flowequation     = flowequation();
 			md.debug            = debug();
-			md.verbose          = verbose('solution',true,'qmu',true,'control',true);
+			md.verbose          = verbose();
 			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.toolkits         = toolkits();
 			md.cluster          = generic();
 			md.balancethickness = balancethickness();
 			md.diagnostic       = diagnostic();
-			md.hydrology        = hydrology();
+			md.hydrology        = hydrologyshreve();
 			md.prognostic       = prognostic();
 			md.thermal          = thermal();
 			md.steadystate      = steadystate();
 			md.transient        = transient();
+			md.gia              = gia();
 			md.autodiff         = autodiff();
 			md.flaim            = flaim();
@@ -1115,5 +1129,5 @@
 			disp(sprintf('%19s: %-22s -- %s','verbose'         ,['[1x1 ' class(obj.verbose) ']'],'verbosity level in solve'));
 			disp(sprintf('%19s: %-22s -- %s','settings'        ,['[1x1 ' class(obj.settings) ']'],'settings properties'));
-			disp(sprintf('%19s: %-22s -- %s','solver'          ,['[1x1 ' class(obj.solver) ']'],'PETSc options for each solution'));
+			disp(sprintf('%19s: %-22s -- %s','toolkits'          ,['[1x1 ' class(obj.toolkits) ']'],'PETSc options for each solution'));
 			disp(sprintf('%19s: %-22s -- %s','cluster'         ,['[1x1 ' class(obj.cluster) ']'],'cluster parameters (number of cpus...)'));
 			disp(sprintf('%19s: %-22s -- %s','balancethickness',['[1x1 ' class(obj.balancethickness) ']'],'parameters for balancethickness solution'));
@@ -1125,4 +1139,5 @@
 			disp(sprintf('%19s: %-22s -- %s','steadystate'     ,['[1x1 ' class(obj.steadystate) ']'],'parameters for steadystate solution'));
 			disp(sprintf('%19s: %-22s -- %s','transient'       ,['[1x1 ' class(obj.transient) ']'],'parameters for transient solution'));
+			disp(sprintf('%19s: %-22s -- %s','gia'       ,['[1x1 ' class(obj.gia) ']'],'parameters for gia solution'));
 			disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(obj.autodiff) ']'],'automatic differentiation parameters'));
 			disp(sprintf('%19s: %-22s -- %s','flaim'           ,['[1x1 ' class(obj.flaim) ']'],'flaim parameters'));
@@ -1134,18 +1149,93 @@
 		end % }}}
 		function memory(obj) % {{{
-			
-		disp(sprintf('\nMemory imprint: '));
-
-		objects=fields(obj);
-		memory=0;
+
+		disp(sprintf('\nMemory imprint:\n'));
+
+		fields=properties('model');
+		mem=0;
+
+		for i=1:length(fields),
+			field=obj.(fields{i});
+			s=whos('field'); 
+			mem=mem+s.bytes/1e6;
+			disp(sprintf('%19s: %6.2f Mb',fields{i},s.bytes/1e6));
+		end
+		disp(sprintf('%19s--%10s','--------------','--------------'));
+		disp(sprintf('%19s: %g Mb','Total',mem));
+		end % }}}
+		function netcdf(obj,filename) % {{{
+		%NETCDF - save model as netcdf
+		%
+		%   Usage:
+		%      netcdf(md,filename)
+		%
+		%   Example:
+		%      netcdf(md,'model.nc');
+
+		disp('Saving model as NetCDF');
+		%1. Create NetCDF file
+		ncid=netcdf.create(filename,'CLOBBER');
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Conventions','CF-1.4');
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Title',['ISSM model (' obj.miscellaneous.name ')']);
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Author',getenv('USER'));
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Date',datestr(now));
+
+		%Preallocate variable id, needed to write variables in netcdf file
+		var_id=zeros(1000,1);%preallocate
+
+		for step=1:2,
+			counter=0;
+			[var_id,counter]=structtonc(ncid,'md',obj,0,var_id,counter,step);
+			if step==1, netcdf.endDef(ncid); end
+		end
+
+		if counter>1000,
+			warning(['preallocation of var_id need to be updated from ' num2str(1000) ' to ' num2str(counter)]);
+		end
+
+		netcdf.close(ncid)
+		end % }}}
+		function xylim(obj) % {{{
+
+			xlim([min(obj.mesh.x) max(obj.mesh.x)]);
+			ylim([min(obj.mesh.y) max(obj.mesh.y)])
+		end % }}}
+		function md=upload(md) % {{{
+		%the goal of this routine is to upload the model onto a server, and to empty it.
+		%So first, save the model with a unique name and upload the file to the server: 
+		random_part=fix(rand(1)*10000);
+		id=[md.miscellaneous.name '-' regexprep(datestr(now),'[^\w'']','') '-' num2str(random_part)  '-' getenv('USER') '-' oshostname() '.upload']; 
+		eval(['save ' id ' md']);
+
+		%Now, upload the file: 
+		issmscpout(md.settings.upload_server,md.settings.upload_path,md.settings.upload_login,md.settings.upload_port,{id},1);
+
+		%Now, empty this model of everything except settings, and record name of file we just uploaded!
+		settings_back=md.settings;
+		md=model();
+		md.settings=settings_back;
+		md.settings.upload_filename=id;
+
+		%get locally rid of file that was uploaded
+		eval(['delete ' id]);
+
+
+		end % }}}
+		function md=download(md) % {{{
 		
-		for i=1:length(objects),
-			field=objects{i};
-			realobject=obj.(field);
-			s=whos('realobject'); 
-			memory=memory+s.bytes/1e6;
-			disp(sprintf('%19s: %g Mb',field,s.bytes/1e6));
-		end
-		disp(sprintf('Overall: %g Mb',memory));
+		%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});
+
+		name=md.settings.upload_filename;
+
+		%Now, load this model: 
+		md=loadmodel(md.settings.upload_filename);
+
+		%get locally rid of file that was downloaded
+		eval(['delete ' name]);
+
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/model/model.py
===================================================================
--- /issm/trunk/src/m/classes/model/model.py	(revision 15395)
+++ /issm/trunk/src/m/classes/model/model.py	(revision 15396)
@@ -18,14 +18,15 @@
 from verbose import verbose
 from settings import settings
-from solver import solver
+from toolkits import toolkits
 from generic import generic
 from balancethickness import balancethickness
 from diagnostic import diagnostic
 from groundingline import groundingline
-from hydrology import hydrology
+from hydrologyshreve import hydrologyshreve
 from prognostic import prognostic
 from thermal import thermal
 from steadystate import steadystate
 from transient import transient
+from gia import gia
 from autodiff import autodiff
 from flaim import flaim
@@ -50,6 +51,5 @@
 class model(object):
 	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self):#{{{
 		self.mesh             = mesh()
 		self.mask             = mask()
@@ -66,11 +66,7 @@
 
 		self.debug            = debug()
-		self.verbose          = verbose('solution',True,'qmu',True,'control',True)
+		self.verbose          = verbose()
 		self.settings         = settings()
-		self.solver           = solver()
-		if ismumps():
-			self.solver.addoptions(DiagnosticVertAnalysisEnum(),mumpsoptions())
-		else:
-			self.solver.addoptions(DiagnosticVertAnalysisEnum(),iluasmoptions())
+		self.toolkits         = toolkits()
 		self.cluster          = generic()
 
@@ -78,9 +74,10 @@
 		self.diagnostic       = diagnostic()
 		self.groundingline    = groundingline()
-		self.hydrology        = hydrology()
+		self.hydrology        = hydrologyshreve()
 		self.prognostic       = prognostic()
 		self.thermal          = thermal()
 		self.steadystate      = steadystate()
 		self.transient        = transient()
+		self.gia              = gia()
 
 		self.autodiff         = autodiff()
@@ -94,5 +91,4 @@
 		self.private          = private()
 		#}}}
-
 	def properties(self):    # {{{
 		# ordered list of properties since vars(self) is random
@@ -112,5 +108,5 @@
 		        'verbose',\
 		        'settings',\
-		        'solver',\
+		        'toolkits',\
 		        'cluster',\
 		        'balancethickness',\
@@ -122,4 +118,5 @@
 		        'steadystate',\
 		        'transient',\
+				  'gia',\
 		        'autodiff',\
 		        'flaim',\
@@ -131,8 +128,5 @@
 		        'private']
 	# }}}
-
-	def __repr__(obj):
-		# {{{ Display
-
+	def __repr__(obj): #{{{
 		#print "Here %s the number: %d" % ("is", 37)
 		string="%19s: %-22s -- %s" % ("mesh","[%s,%s]" % ("1x1",obj.mesh.__class__.__name__),"mesh properties")
@@ -151,5 +145,5 @@
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("verbose","[%s,%s]" % ("1x1",obj.verbose.__class__.__name__),"verbosity level in solve"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("settings","[%s,%s]" % ("1x1",obj.settings.__class__.__name__),"settings properties"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("solver","[%s,%s]" % ("1x1",obj.solver.__class__.__name__),"PETSc options for each solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("toolkits","[%s,%s]" % ("1x1",obj.toolkits.__class__.__name__),"PETSc options for each solution"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("cluster","[%s,%s]" % ("1x1",obj.cluster.__class__.__name__),"cluster parameters (number of cpus...)"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("balancethickness","[%s,%s]" % ("1x1",obj.balancethickness.__class__.__name__),"parameters for balancethickness solution"))
@@ -170,5 +164,4 @@
 		return string
 	# }}}
-
 	def checkmessage(self,string):    # {{{
 		print ("model not consistent: %s" % string)
@@ -176,5 +169,4 @@
 		return self
 	# }}}
-
 	def extract(md,area):    # {{{
 		"""
@@ -450,5 +442,4 @@
 		return md2
 	# }}}
-
 	def extrude(md,*args):    # {{{
 		"""
@@ -634,4 +625,5 @@
 		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]
@@ -657,4 +649,6 @@
 		md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node')
 		md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node')
+		md.gia.mantle_viscosity=project3d(md,'vector',md.gia.mantle_viscosity,'type','node')
+		md.gia.lithosphere_thickness=project3d(md,'vector',md.gia.lithosphere_thickness,'type','node')
 		md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node')
 		md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node')
@@ -697,3 +691,2 @@
 		return md
 		# }}}
-
Index: /issm/trunk/src/m/classes/oldclasses/hydrology.m
===================================================================
--- /issm/trunk/src/m/classes/oldclasses/hydrology.m	(revision 15396)
+++ /issm/trunk/src/m/classes/oldclasses/hydrology.m	(revision 15396)
@@ -0,0 +1,67 @@
+%HYDROLOGY class definition
+%
+%   Usage:
+%      hydrology=hydrology();
+
+classdef hydrology
+	properties (SetAccess=public) 
+		spcwatercolumn = NaN;
+		n              = 0;
+		CR             = 0;
+		p              = 0;
+		q              = 0;
+		kn             = 0;
+		stabilization  = 0;
+	end
+	methods
+		function obj = hydrology(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Parameters from Johnson's 2002 thesis, section 3.5.4			 
+			obj.n=.02;			 
+			obj.CR=.01;
+			obj.p=2;		 
+			obj.q=1;		 
+			obj.kn=0;
+
+			%Type of stabilization to use 0:nothing 1:artificial_diffusivity
+			obj.stabilization=1;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(HydrologyAnalysisEnum(),analyses), return; end
+
+			md = checkfield(md,'hydrology.spcwatercolumn','forcing',1);
+			md = checkfield(md,'hydrology.stabilization','>=',0);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   hydrology solution parameters:'));
+
+			fielddisplay(obj,'spcwatercolumn','water thickness constraints (NaN means no constraint)');
+			fielddisplay(obj,'n','Manning roughness coefficient');
+			fielddisplay(obj,'CR','tortuosity parameter');
+			fielddisplay(obj,'p','dimensionless exponent in Manning velocity formula');
+			fielddisplay(obj,'q','dimensionless exponent in Manning velocity formula');
+			fielddisplay(obj,'kn','parameter in effective pressure formula');
+			fielddisplay(obj,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','n','format','Double');
+			WriteData(fid,'object',obj,'fieldname','CR','format','Double');
+			WriteData(fid,'object',obj,'fieldname','p','format','Double');
+			WriteData(fid,'object',obj,'fieldname','q','format','Double');
+			WriteData(fid,'object',obj,'fieldname','kn','format','Double');
+			WriteData(fid,'object',obj,'fieldname','stabilization','format','Double');
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/organizer.py
===================================================================
--- /issm/trunk/src/m/classes/organizer.py	(revision 15395)
+++ /issm/trunk/src/m/classes/organizer.py	(revision 15396)
@@ -63,5 +63,4 @@
 			self.trunkprefix=trunkprefix
 	#}}}
-
 	def __repr__(self):    # {{{
 		s =""
@@ -75,5 +74,4 @@
 				s+="%s\n" % "   step #%2i: '%s'",step['id'],step['string']
 	#}}}
-
 	def load(self,string):    # {{{
 
@@ -93,5 +91,4 @@
 		return md
 	#}}}
-
 	def loadmodel(self,string):    # {{{
 
@@ -118,5 +115,4 @@
 			raise IOerror("Could not find '%s'" % path)
 	#}}}
-
 	def perform(self,string):    # {{{
 
@@ -153,5 +149,4 @@
 		return bool
 	#}}}
-
 	def savemodel(self,md):    # {{{
 
@@ -174,3 +169,2 @@
 		savevars(name,'md',md)
 	#}}}
-
Index: /issm/trunk/src/m/classes/pairoptions.m
===================================================================
--- /issm/trunk/src/m/classes/pairoptions.m	(revision 15395)
+++ /issm/trunk/src/m/classes/pairoptions.m	(revision 15396)
@@ -33,5 +33,5 @@
 			%check length of input
 			if mod((nargin-1),2),
-				error('error: an even number of options is required') 
+				error('Invalid parameter/value pair arguments') 
 			end
 			numoptions = (nargin-1)/2;
Index: /issm/trunk/src/m/classes/pairoptions.py
===================================================================
--- /issm/trunk/src/m/classes/pairoptions.py	(revision 15395)
+++ /issm/trunk/src/m/classes/pairoptions.py	(revision 15396)
@@ -11,5 +11,5 @@
 	"""
 
-	def __init__(self,*arg):
+	def __init__(self,*arg): # {{{
 		self.functionname = ''
 		self.list         = OrderedDict()
@@ -26,74 +26,4 @@
 			self.buildlist(*arg)
 	# }}}
-
-	def buildlist(self,*arg):    # {{{
-		"""BUILDLIST - build list of objects from input"""
-
-		#check length of input
-		if len(arg) % 2:
-			raise TypeError('error: an even number of options is required') 
-		numoptions = len(arg)/2
-
-		#go through arg and build list of objects
-		for i in xrange(numoptions):
-			if isinstance(arg[2*i],(str,unicode)):
-				self.list[arg[2*i]] = arg[2*i+1];
-			else:
-				#option is not a string, ignore it
-				print "WARNING: option number %d is not a string and will be ignored." % (i+1)
-	# }}}
-
-	def addfield(self,field,value):    # {{{
-		"""ADDFIELD - add a field to an options list"""
-		if isinstance(field,(str,unicode)):
-			if field in self.list:
-				print "WARNING: field '%s' with value=%s exists and will be overwritten with value=%s." % (field,str(self.list[field]),str(value))
-			self.list[field] = value
-	# }}}
-
-	def addfielddefault(self,field,value):    # {{{
-		"""ADDFIELDDEFAULT - add a field to an options list if it does not already exist"""
-		if isinstance(field,(str,unicode)):
-			if field not in self.list:
-				self.list[field] = value
-	# }}}
-
-	def AssignObjectFields(self,obj2):    # {{{
-		"""ASSIGNOBJECTFIELDS - assign object fields from options"""
-		for item in self.list.iteritems():
-			if item[0] in dir(obj2):
-				setattr(obj2,item[0],item[1])
-			else:
-				print "WARNING: field '%s' is not a property of '%s'." % (item[0],type(obj2))
-		return obj2
-	# }}}
-
-	def changefieldvalue(self,field,newvalue):    # {{{
-		"""CHANGEOPTIONVALUE - change the value of an option in an option list"""
-
-		self.list[field]=newvalue;
-	# }}}
-
-#	function obj = deleteduplicates(obj,warn) % {{{
-#	%DELETEDUPLICATES - delete duplicates in an option list
-#
-#		%track the first occurrence of each option
-#		[dummy lines]=unique(obj.list(:,1),'first');
-#		clear dummy
-#
-#		%warn user if requested
-#		if warn,
-#			numoptions=size(obj.list,1);
-#			for i=1:numoptions,
-#				if ~ismember(i,lines),
-#					disp(['WARNING: option ' obj.list{i,1} ' appeared more than once. Only its first occurrence will be kept'])
-#				end
-#			end
-#		end
-#
-#		%remove duplicates from the options list
-#		obj.list=obj.list(lines,:);
-#	end % }}}
-
 	def __repr__(self):    # {{{
 		s="   functionname: '%s'\n" % self.functionname
@@ -111,5 +41,47 @@
 		return s
 	# }}}
+	def buildlist(self,*arg):    # {{{
+		"""BUILDLIST - build list of objects from input"""
 
+		#check length of input
+		if len(arg) % 2:
+			raise TypeError('Invalid parameter/value pair arguments') 
+		numoptions = len(arg)/2
+
+		#go through arg and build list of objects
+		for i in xrange(numoptions):
+			if isinstance(arg[2*i],(str,unicode)):
+				self.list[arg[2*i]] = arg[2*i+1];
+			else:
+				#option is not a string, ignore it
+				print "WARNING: option number %d is not a string and will be ignored." % (i+1)
+	# }}}
+	def addfield(self,field,value):    # {{{
+		"""ADDFIELD - add a field to an options list"""
+		if isinstance(field,(str,unicode)):
+			if field in self.list:
+				print "WARNING: field '%s' with value=%s exists and will be overwritten with value=%s." % (field,str(self.list[field]),str(value))
+			self.list[field] = value
+	# }}}
+	def addfielddefault(self,field,value):    # {{{
+		"""ADDFIELDDEFAULT - add a field to an options list if it does not already exist"""
+		if isinstance(field,(str,unicode)):
+			if field not in self.list:
+				self.list[field] = value
+	# }}}
+	def AssignObjectFields(self,obj2):    # {{{
+		"""ASSIGNOBJECTFIELDS - assign object fields from options"""
+		for item in self.list.iteritems():
+			if item[0] in dir(obj2):
+				setattr(obj2,item[0],item[1])
+			else:
+				print "WARNING: field '%s' is not a property of '%s'." % (item[0],type(obj2))
+		return obj2
+	# }}}
+	def changefieldvalue(self,field,newvalue):    # {{{
+		"""CHANGEOPTIONVALUE - change the value of an option in an option list"""
+
+		self.list[field]=newvalue;
+	# }}}
 	def exist(self,field):    # {{{
 		"""EXIST - check if the option exist"""
@@ -127,19 +99,4 @@
 			return False
 	# }}}
-
-	#def fieldoccurrences(self,field): #{{{
-	#	'''
-	#	FIELDOCCURRENCES - get number of occurrence of a field
-	#	'''
-	#
-	#	#check input 
-	#	if not isinstance(field,(str,unicode)):
-	#		raise TypeError("fieldoccurrences error message: field should be a string")
-
-	#	#get number of occurrence
-	#	# ??
-	#	#return num
-	#	#% }}}
-
 	def getfieldvalue(self,field,default=None):    # {{{
 		"""
@@ -174,5 +131,4 @@
 		return value
 	# }}}
-
 	def removefield(self,field,warn):    # {{{
 		"""
@@ -196,6 +152,5 @@
 				print "removefield info: option '%s' has been removed from the list of options." % field
 	# }}}
-
-	def marshall(self,fid,firstindex):    # {{{
+	def marshall(self,md,fid,firstindex):    # {{{
 
 		for i,item in enumerate(self.list.iteritems()):
@@ -214,3 +169,2 @@
 				raise TypeError("Cannot marshall option '%s': format not supported yet." % name)
 	# }}}
-
Index: /issm/trunk/src/m/classes/planetmesh.m
===================================================================
--- /issm/trunk/src/m/classes/planetmesh.m	(revision 15395)
+++ /issm/trunk/src/m/classes/planetmesh.m	(revision 15396)
@@ -1,3 +1,3 @@
-%MESH class definition
+%PLANETMESH class definition
 %
 %   Usage:
@@ -17,7 +17,4 @@
 		numberofelements            = 0;
 		numberofvertices            = 0;
-
-		lat                         = NaN
-		long                        = NaN
 
 		vertexconnectivity          = NaN
@@ -64,5 +61,4 @@
 			md = checkfield(md,'planetmesh.numberofelements','>',0);
 			md = checkfield(md,'planetmesh.numberofvertices','>',0);
-			%no checks for numberofedges lat long and hemisphere
 			if (md.planetmesh.dimension==2),
 				md = checkfield(md,'planetmesh.average_vertex_connectivity','>=',9,'message','''planetmesh.average_vertex_connectivity'' should be at least 9 in 2d');
@@ -92,11 +88,11 @@
 			fielddisplay(obj,'numberofelements','number of elements');
 			fielddisplay(obj,'numberofvertices','number of vertices');
-			fielddisplay(obj,'elements','index into (x,y,z), coordinates of the vertices');
-			fielddisplay(obj,'x','vertices x coordinate');
-			fielddisplay(obj,'y','vertices y coordinate');
-			fielddisplay(obj,'z','vertices z coordinate');
-			fielddisplay(obj,'r','vertices r coordinate');
-			fielddisplay(obj,'theta','vertices theta coordinate');
-			fielddisplay(obj,'phi','vertices phi coordinate');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'z','vertices z coordinate [m]');
+			fielddisplay(obj,'r','vertices r coordinate [m]');
+			fielddisplay(obj,'theta','vertices theta coordinate [degrees]');
+			fielddisplay(obj,'phi','vertices phi coordinate [degrees]');
 
 			disp(sprintf('\n      Properties:'));
@@ -109,5 +105,5 @@
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','x','format','DoubleMat','mattype',1);
 			WriteData(fid,'object',obj,'fieldname','y','format','DoubleMat','mattype',1);
Index: /issm/trunk/src/m/classes/plotoptions.m
===================================================================
--- /issm/trunk/src/m/classes/plotoptions.m	(revision 15395)
+++ /issm/trunk/src/m/classes/plotoptions.m	(revision 15396)
@@ -45,5 +45,5 @@
 			 %check length of input
 			 if mod((nargin-1),2),
-				 error('buildlist error message: an even number of plotoptions is required')
+				 error('Invalid parameter/value pair arguments')
 			 end
 
@@ -52,18 +52,19 @@
 			 numoptions = (nargin-1)/2;
 			 rawlist=cell(numoptions,2);
+			 counter=1;
 			 for i=1:numoptions,
-				 if ischar(varargin{2*i-1}),
-					 rawlist{i,1}=varargin{2*i-1};
-					 rawlist{i,2}=varargin{2*i};
+				 optionname = varargin{2*i-1};
+				 optionval  = varargin{2*i};
+				 if ischar(optionname),
+					 rawlist{counter,1}=optionname;
+					 rawlist{counter,2}=optionval;
+					 counter=counter+1;
 				 else
 					 %option is not a string, ignore it
 					 disp(['WARNING: option number ' num2str(i) ' is not a string, it will be ignored']);
-					 rawlist(i,:)=[];
+					 rawlist(counter,:)=[];
 					 continue
 				 end
 			 end
-
-			 %get figure number
-			 opt.figurenumber=getfieldvalue(rawoptions,'figure',1);
 
 			 %get number of data to be plotted
@@ -162,4 +163,9 @@
 				 opt.list{i}=deleteduplicates(opt.list{i},1);
 			 end
+
+			 %Get figure number (should be in options for subplot 1)
+			 opt.figurenumber=getfieldvalue(opt.list{1},'figure',1);
+			 removefield(opt.list{1},'figure',0);
+
 		 end
 		 %}}}
Index: /issm/trunk/src/m/classes/plotoptions.py
===================================================================
--- /issm/trunk/src/m/classes/plotoptions.py	(revision 15395)
+++ /issm/trunk/src/m/classes/plotoptions.py	(revision 15396)
@@ -10,5 +10,5 @@
 	'''
 
-	def __init__(self,*arg):
+	def __init__(self,*arg):# {{{
 		self.numberofplots = 0
 		self.figurenumber  = 1
@@ -16,5 +16,5 @@
 
 		self.buildlist(*arg)
-
+		#}}}
 	def __repr__(self): #{{{
 		s="\n"
@@ -38,5 +38,5 @@
 		#check length of input
 		if len(arg) % 2:
-			raise TypeError('error: an even number of options is required')
+			raise TypeError('Invalid parameter/value pair arguments')
 
 		#go through args and build list (like pairoptions)
@@ -54,4 +54,5 @@
 		#get figure number 
 		self.figurenumber=rawoptions.getfieldvalue('figure',1)
+		rawoptions.removefield('figure',0)
 
 		#get number of subplots 
Index: /issm/trunk/src/m/classes/private.py
===================================================================
--- /issm/trunk/src/m/classes/private.py	(revision 15395)
+++ /issm/trunk/src/m/classes/private.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from collections import OrderedDict
 from fielddisplay import fielddisplay
@@ -13,7 +12,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.isconsistent = True
 		self.runtimename  = ''
@@ -25,6 +22,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string='   private parameters: do not change'
 
@@ -35,12 +31,8 @@
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		return md
 	# }}}
-
Index: /issm/trunk/src/m/classes/prognostic.m
===================================================================
--- /issm/trunk/src/m/classes/prognostic.m	(revision 15395)
+++ /issm/trunk/src/m/classes/prognostic.m	(revision 15396)
@@ -53,8 +53,8 @@
 		function disp(obj) % {{{
 			disp(sprintf('   Prognostic solution parameters:'));
-			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint)');
-			fielddisplay(obj,'min_thickness','minimum ice thickness allowed');
+			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');
+			fielddisplay(obj,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin');
 
 			disp(sprintf('\n      %s','Penalty options:'));
@@ -64,6 +64,6 @@
 
 		end % }}}
-		function marshall(obj,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1);
+		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());
Index: /issm/trunk/src/m/classes/prognostic.py
===================================================================
--- /issm/trunk/src/m/classes/prognostic.py	(revision 15395)
+++ /issm/trunk/src/m/classes/prognostic.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -14,7 +13,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.spcthickness           = float('NaN')
 		self.min_thickness          = 0
@@ -29,18 +26,15 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string='   Prognostic solution parameters:'
-		string="%s\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(self,'min_thickness','minimum ice thickness allowed'))
+		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,'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):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
@@ -58,5 +52,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -74,7 +67,6 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1)
+	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())
@@ -84,3 +76,2 @@
 		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
 	# }}}
-
Index: /issm/trunk/src/m/classes/qmu.m
===================================================================
--- /issm/trunk/src/m/classes/qmu.m	(revision 15395)
+++ /issm/trunk/src/m/classes/qmu.m	(revision 15396)
@@ -140,5 +140,5 @@
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','isdakota','format','Boolean');
 			if ~obj.isdakota, 
Index: /issm/trunk/src/m/classes/qmu.py
===================================================================
--- /issm/trunk/src/m/classes/qmu.py	(revision 15395)
+++ /issm/trunk/src/m/classes/qmu.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 from collections import OrderedDict
@@ -16,7 +15,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.isdakota                    = 0
 		self.variables                   = OrderedDict()
@@ -40,7 +37,5 @@
 
 		#}}}
-
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
@@ -139,5 +134,5 @@
 		return s
 	# }}}
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','isdakota','format','Boolean')
 		if not self.isdakota:
@@ -156,3 +151,2 @@
 		WriteData(fid,'data',flag,'enum',QmuMassFluxSegmentsPresentEnum(),'format','Boolean');
 	# }}}
-
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 15395)
+++ /issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 15396)
@@ -350,5 +350,6 @@
                 param_write(fid,sbeg,'seed','             = ','\n',dm.params);
                 param_write(fid,sbeg,'fixed_seed','','\n',dm.params);
-                if (str2num(dakotaversion())>4.2)
+                dver=textscan(dakotaversion(),'%[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);
                 end
Index: /issm/trunk/src/m/classes/radaroverlay.m
===================================================================
--- /issm/trunk/src/m/classes/radaroverlay.m	(revision 15395)
+++ /issm/trunk/src/m/classes/radaroverlay.m	(revision 15396)
@@ -26,6 +26,6 @@
 
 			fielddisplay(obj,'pwr','radar power image (matrix)');
-			fielddisplay(obj,'x','corresponding x coordinates');
-			fielddisplay(obj,'y','corresponding y coordinates');
+			fielddisplay(obj,'x','corresponding x coordinates [m]');
+			fielddisplay(obj,'y','corresponding y coordinates [m]');
 
 		end % }}}
Index: /issm/trunk/src/m/classes/radaroverlay.py
===================================================================
--- /issm/trunk/src/m/classes/radaroverlay.py	(revision 15395)
+++ /issm/trunk/src/m/classes/radaroverlay.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 
@@ -10,7 +9,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.pwr = float('NaN')
 		self.x   = float('NaN')
@@ -21,16 +18,12 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string='   radaroverlay parameters:'
 		string="%s\n%s"%(string,fielddisplay(self,'pwr','radar power image (matrix)'))
-		string="%s\n%s"%(string,fielddisplay(self,'x','corresponding x coordinates'))
-		string="%s\n%s"%(string,fielddisplay(self,'y','corresponding y coordinates'))
+		string="%s\n%s"%(string,fielddisplay(self,'x','corresponding x coordinates [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'y','corresponding y coordinates [m]'))
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
Index: /issm/trunk/src/m/classes/results.py
===================================================================
--- /issm/trunk/src/m/classes/results.py	(revision 15395)
+++ /issm/trunk/src/m/classes/results.py	(revision 15396)
@@ -17,5 +17,4 @@
 		pass
 	# }}}
-
 	def __repr__(self):    # {{{
 		s ="   Model results:\n"
@@ -44,16 +43,12 @@
 		return s
 	# }}}
-
 	def setdefaultparameters(self):    # {{{
 		#do nothing
 		return self
 	# }}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		pass
 	# }}}
-
Index: /issm/trunk/src/m/classes/rifts.m
===================================================================
--- /issm/trunk/src/m/classes/rifts.m	(revision 15395)
+++ /issm/trunk/src/m/classes/rifts.m	(revision 15396)
@@ -54,5 +54,5 @@
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 
 			%Process rift info
Index: /issm/trunk/src/m/classes/rifts.py
===================================================================
--- /issm/trunk/src/m/classes/rifts.py	(revision 15395)
+++ /issm/trunk/src/m/classes/rifts.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 from fielddisplay import fielddisplay
@@ -15,7 +14,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.riftstruct     = []
 		self.riftproperties = []
@@ -25,6 +22,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string='   rifts parameters:'
 
@@ -33,10 +29,7 @@
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
@@ -61,6 +54,5 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 
 		#Process rift info
@@ -90,3 +82,2 @@
 		WriteData(fid,'data',data,'enum',RiftsRiftstructEnum(),'format','DoubleMat','mattype',3)
 	# }}}
-
Index: /issm/trunk/src/m/classes/settings.m
===================================================================
--- /issm/trunk/src/m/classes/settings.m	(revision 15395)
+++ /issm/trunk/src/m/classes/settings.m	(revision 15396)
@@ -11,4 +11,10 @@
 		output_frequency    = 0;
 		waitonlock          = 0;
+		upload_server       = '';
+		upload_path         = '';
+		upload_login        = '';
+		upload_port         = 0;
+		upload_filename     = '';
+
 	end
 	methods
@@ -40,4 +46,8 @@
 			%0 to deactivate
 			obj.waitonlock=Inf;
+		
+			%upload options: 
+			upload_port         = 0;
+
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -57,8 +67,13 @@
 			fielddisplay(obj,'results_as_patches','provide results as patches for each element (0 or 1)');
 			fielddisplay(obj,'output_frequency','frequency at which results are saved in all solutions with multiple time_steps');
-			fielddisplay(obj,'waitonlock','maximum number of minutes to wait for batch results, or return 0');
+			fielddisplay(obj,'waitonlock','maximum number of minutes to wait for batch results (NaN to deactivate)');
+			fielddisplay(obj,'upload_server','server hostname where model should be uploaded');
+			fielddisplay(obj,'upload_path','path on server where model should be uploaded');
+			fielddisplay(obj,'upload_login','server login');
+			fielddisplay(obj,'upload_port','port login (default is 0)');
+			fielddisplay(obj,'upload_filename','unique id generated when uploading the file to server');
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','io_gather','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','lowmem','format','Boolean');
Index: /issm/trunk/src/m/classes/settings.py
===================================================================
--- /issm/trunk/src/m/classes/settings.py	(revision 15395)
+++ /issm/trunk/src/m/classes/settings.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -13,7 +12,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.io_gather           = 0
 		self.lowmem              = 0
@@ -26,6 +23,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string="   general settings parameters:"
 
@@ -37,7 +33,5 @@
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#are we short in memory ? (0 faster but requires more memory)
@@ -61,5 +55,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		md = checkfield(md,'settings.io_gather','numel',[1],'values',[0,1])
@@ -71,6 +64,5 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','io_gather','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','lowmem','format','Boolean')
@@ -82,3 +74,2 @@
 			WriteData(fid,'enum',SettingsWaitonlockEnum(),'data',False,'format','Boolean');
 	# }}}
-
Index: sm/trunk/src/m/classes/solver.m
===================================================================
--- /issm/trunk/src/m/classes/solver.m	(revision 15395)
+++ 	(revision )
@@ -1,114 +1,0 @@
-%SOLVER class definition
-%
-%   Usage:
-%      obj=solver();
-
-classdef solver < dynamicprops
-    properties (SetAccess=public) 
-		 NoneAnalysis = struct();
-		 %The other properties are dynamic
-	 end
-	 methods
-		 function obj = solver(varargin) % {{{
-			 switch nargin
-				 case 0
-					 obj=setdefaultparameters(obj);
-				 otherwise
-					 error('constructor not supported');
-				 end
-			 end % }}}
-		 function obj = addoptions(obj,analysis,varargin) % {{{
-		 % Usage example:
-		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum(),stokesoptions());
-		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum());
-
-			 %Convert analysis from enum to string
-			 analysis=EnumToString(analysis);
-
-			 %Create dynamic property if property does not exist yet
-			 if ~ismember(analysis,properties(obj)),
-				 obj.addprop(analysis);
-			 end
-
-			 %Add solver options to analysis
-			 if nargin==3, obj.(analysis) = varargin{1}; end
-		 end
-		 %}}}
-		 function obj = setdefaultparameters(obj) % {{{
-
-			 %MUMPS is the default solver
-			 if ismumps(),
-				 obj.NoneAnalysis=mumpsoptions();
-			 else
-				 obj.NoneAnalysis=iluasmoptions();
-			 end
-
-		 end % }}}
-		 function disp(obj) % {{{
-			 analyses=properties(obj);
-			 disp(sprintf('List of solver options per analysis:\n'));
-			 for i=1:numel(analyses),
-				 analysis=analyses{i};
-				 disp([analysis ':']);
-				 disp(obj.(analysis));
-			 end
-		 end % }}}
-		 function md = checkconsistency(obj,md,solution,analyses) % {{{
-			 analyses=properties(obj);
-			 for i=1:numel(analyses),
-				 if isempty(fieldnames(obj.(analyses{i})))
-					 md = checkmessage(md,['md.solver.' analyses{i} ' is empty']);
-				 end
-			 end
-		 end % }}}
-		 function PetscFile(solver,filename) % {{{
-		 %PETSCFILE - build petsc file
-		 %
-		 %   Build a Petsc compatible options file, from the solver model field  + return options string
-		 %
-		 %   Usage:     PetscFile(solver,filename);
-
-			 %open file for writing
-			 fid=fopen(filename,'w');
-			 if fid==-1,
-				 error(['PetscFile error: could not open ' filename ' for writing']);
-			 end
-
-			 %write header
-			 fprintf(fid,'%s%s%s\n','%Petsc options file: ',filename,' written from Matlab solver array');
-
-			 %start writing options
-			 analyses=properties(solver);
-			 for i=1:numel(analyses),
-				 analysis=analyses{i};
-				 options=solver.(analysis);
-
-				 %first write analysis:
-				 fprintf(fid,'\n+%s\n',analysis); %append a + to recognize it's an analysis enum
-
-				 %now, write options
-				 optionslist=fieldnames(options);
-				 for j=1:numel(optionslist),
-					 optionname=optionslist{j};
-					 optionvalue=options.(optionname);
-
-					 if isempty(optionvalue),
-						 %this option has only one argument
-						 fprintf(fid,'-%s\n',optionname);
-					 else
-						 %option with value. value can be string or scalar
-						 if isnumeric(optionvalue),
-							 fprintf(fid,'-%s %g\n',optionname,optionvalue);
-						 elseif ischar(optionvalue),
-							 fprintf(fid,'-%s %s\n',optionname,optionvalue);
-						 else
-							 error(['PetscFile error: option ' optionname ' is not well formatted']);
-						 end
-					 end
-				 end
-			 end
-
-			 fclose(fid);
-		 end %}}}
-	 end
- end
Index: sm/trunk/src/m/classes/solver.py
===================================================================
--- /issm/trunk/src/m/classes/solver.py	(revision 15395)
+++ 	(revision )
@@ -1,106 +1,0 @@
-from ismumps import *
-from mumpsoptions import *
-from iluasmoptions import *
-from EnumToString import EnumToString
-from fielddisplay import fielddisplay
-from EnumDefinitions import *
-from checkfield import *
-from MatlabFuncs import *
-
-class solver(object):
-	"""
-	SOLVER class definition
-
-	   Usage:
-	      obj=solver();
-	"""
-
-	def __init__(self):    # {{{
-		#MUMPS is the default solver
-		if ismumps():
-			self.NoneAnalysis=mumpsoptions()
-		else:
-			self.NoneAnalysis=iluasmoptions()
-
-		#The other properties are dynamic
-	# }}}
-
-	def addoptions(self,analysis,*args):    # {{{
-		# Usage example:
-		#    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum(),stokesoptions());
-		#    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum());
-
-		#Convert analysis from enum to string
-		[analysis]=EnumToString(analysis)
-
-		#Create dynamic property if property does not exist yet
-		if not hasattr(self,analysis):
-#			exec("self.%s = None" % analysis)
-			setattr(self,analysis,None)
-
-		#Add solver options to analysis
-		if len(args)==1:
-			setattr(self,analysis,args[0])
-
-		return self
-	# }}}
-
-	def __repr__(self):    # {{{
-		s ="List of solver options per analysis:\n\n"
-		for analysis in vars(self).iterkeys():
-			s+="%s\n" % fielddisplay(self,analysis,'')
-
-		return s
-	# }}}
-
-	def checkconsistency(self,md,solution,analyses):    # {{{
-		for analysis in vars(self).iterkeys():
-			if not getattr(self,analysis):
-				md.checkmessage("md.solver.%s is empty" % analysis)
-
-		return md
-	# }}}
-
-	def PetscFile(self,filename):    # {{{
-		"""
-		PETSCFILE - build petsc file
-
-		   Build a Petsc compatible options file, from the solver model field  + return options string
-
-		   Usage:     PetscFile(solver,filename);
-		"""
-
-		#open file for writing
-		try:
-			fid=open(filename,'w')
-		except IOError as e:
-			raise IOError("PetscFile error: could not open '%s' for writing." % filename)
-
-		#write header
-		fid.write("%s%s%s\n" % ('%Petsc options file: ',filename,' written from Matlab solver array'))
-
-		#start writing options
-		for analysis in vars(self).iterkeys():
-			options=getattr(self,analysis)
-
-			#first write analysis:
-			fid.write("\n+%s\n" % analysis)    #append a + to recognize it's an analysis enum
-
-			#now, write options
-			for optionname,optionvalue in options.iteritems():
-
-				if not optionvalue:
-					#this option has only one argument
-					fid.write("-%s\n" % optionname)
-				else:
-					#option with value. value can be string or scalar
-					if   isinstance(optionvalue,(bool,int,long,float)):
-						fid.write("-%s %g\n" % (optionname,optionvalue))
-					elif isinstance(optionvalue,(str,unicode)):
-						fid.write("-%s %s\n" % (optionname,optionvalue))
-					else:
-						raise TypeError("PetscFile error: option '%s' is not well formatted." % optionname)
-
-		fid.close()
-	# }}}
-
Index: /issm/trunk/src/m/classes/steadystate.m
===================================================================
--- /issm/trunk/src/m/classes/steadystate.m	(revision 15395)
+++ /issm/trunk/src/m/classes/steadystate.m	(revision 15396)
@@ -47,5 +47,5 @@
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','reltol','format','Double');
 			WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
Index: /issm/trunk/src/m/classes/steadystate.py
===================================================================
--- /issm/trunk/src/m/classes/steadystate.py	(revision 15395)
+++ /issm/trunk/src/m/classes/steadystate.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 from fielddisplay import fielddisplay
@@ -14,7 +13,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.reltol            = 0
 		self.maxiter           = 0
@@ -25,6 +22,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string='   steadystate solution parameters:'
 		string="%s\n%s"%(string,fielddisplay(self,'reltol','relative tolerance criterion'))
@@ -33,7 +29,5 @@
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#maximum of steady state iterations
@@ -45,5 +39,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -60,9 +53,7 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','reltol','format','Double')
 		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
 		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
 	# }}}
-
Index: /issm/trunk/src/m/classes/surfaceforcings.m
===================================================================
--- /issm/trunk/src/m/classes/surfaceforcings.m	(revision 15395)
+++ /issm/trunk/src/m/classes/surfaceforcings.m	(revision 15396)
@@ -6,19 +6,21 @@
 classdef surfaceforcings
 	properties (SetAccess=public) 
-		precipitation = NaN;
-		mass_balance  = NaN;
-		ispdd = 0;
-		issmbgradients = 0;
-		isdelta18o = 0;
-		href = NaN;
-		smbref = NaN;
-		b_pos = NaN;
-		b_neg = NaN;
-		monthlytemperatures = NaN;
-		delta18o = NaN;
-		delta18o_surface = NaN;
-		temperatures_presentday = NaN;
-		temperatures_lgm = NaN;
+		precipitation             = NaN;
+		mass_balance              = NaN;
+		ispdd                     = 0;
+		issmbgradients            = 0;
+		isdelta18o                = 0;
+		href                      = NaN;
+		smbref                    = NaN;
+		b_pos                     = NaN;
+		b_neg                     = NaN;
+		monthlytemperatures       = NaN;
+		delta18o                  = NaN;
+		delta18o_surface          = NaN;
+		temperatures_presentday   = NaN;
+		temperatures_lgm          = NaN;
 		precipitations_presentday = NaN;
+		desfac                    = 0.5;
+		s0p                       = 0;
 	end
 	methods
@@ -37,5 +39,6 @@
 		  obj.issmbgradients=0;
 		  obj.isdelta18o=0;
-
+		  obj.desfac=0.5;
+		  obj.s0p=0;
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -45,4 +48,6 @@
 				md = checkfield(md,'surfaceforcings.issmbgradients','numel',[1],'values',[0 1]);
 				if(obj.ispdd)
+				  md = checkfield(md,'surfaceforcings.desfac','<=',1,'numel',1);
+				  md = checkfield(md,'surfaceforcings.s0p','>=',0,'numel',1);
 					if(obj.isdelta18o==0)
 						md = checkfield(md,'surfaceforcings.monthlytemperatures','forcing',1,'NaN',1);
@@ -71,14 +76,21 @@
 			disp(sprintf('   surface forcings parameters:'));
 
+			disp(sprintf('\n   General parameters:'));
 			fielddisplay(obj,'mass_balance','surface mass balance [m/yr ice eq]');
+
+			disp(sprintf('\n   PDD and deltaO18 parameters:'));
 			fielddisplay(obj,'ispdd','is pdd activated (0 or 1, default is 0)');
 			fielddisplay(obj,'isdelta18o','is temperature and precipitation delta18o parametrisation activated (0 or 1, default is 0)');
-			fielddisplay(obj,'monthlytemperatures','monthly surface temperatures [Kelvin], required if pdd is activated and delta18o not activated');
+			fielddisplay(obj,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]');
+			fielddisplay(obj,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]');
+			fielddisplay(obj,'monthlytemperatures','monthly surface temperatures [K], required if pdd is activated and delta18o not activated');
 			fielddisplay(obj,'precipitation','surface precipitation [m/yr water eq]');
-			fielddisplay(obj,'temperatures_presentday','monthly present day surface temperatures [Kelvin], required if pdd is activated and delta18o activated');
-			fielddisplay(obj,'temperatures_lgm','monthly LGM surface temperatures [Kelvin], required if pdd is activated and delta18o activated');
+			fielddisplay(obj,'temperatures_presentday','monthly present day surface temperatures [K], required if pdd is activated and delta18o activated');
+			fielddisplay(obj,'temperatures_lgm','monthly LGM surface temperatures [K], required if pdd is activated and delta18o activated');
 			fielddisplay(obj,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o activated');
 			fielddisplay(obj,'delta18o','delta18o, required if pdd is activated and delta18o activated');
 			fielddisplay(obj,'delta18o_surface','surface elevation of the delta18o site, required if pdd is activated and delta18o activated');
+
+			disp(sprintf('\n   SMB gradients parameters:'));
 			fielddisplay(obj,'issmbgradients','is smb gradients method activated (0 or 1, default is 0)');
 			fielddisplay(obj,'href',' reference elevation from which deviation is used to calculate SMB adjustment in smb gradients method');
@@ -88,10 +100,15 @@
 
 		end % }}}
-		function marshall(obj,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','precipitation','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','mass_balance','format','DoubleMat','mattype',1);
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
 			WriteData(fid,'object',obj,'fieldname','ispdd','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','isdelta18o','format','Boolean');
 			if obj.ispdd,
+				WriteData(fid,'object',obj,'fieldname','desfac','format','Double');
+				WriteData(fid,'object',obj,'fieldname','s0p','format','Double');
 				if obj.isdelta18o
 					WriteData(fid,'object',obj,'fieldname','temperatures_presentday','format','DoubleMat','mattype',1);
@@ -101,14 +118,13 @@
 					WriteData(fid,'object',obj,'fieldname','delta18o','format','DoubleMat','mattype',1);
 				else
-					WriteData(fid,'object',obj,'fieldname','monthlytemperatures','format','DoubleMat','mattype',1);
-					WriteData(fid,'object',obj,'fieldname','precipitation','format','DoubleMat','mattype',1);
+					WriteData(fid,'object',obj,'fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
 				end
 			end
 			WriteData(fid,'object',obj,'fieldname','issmbgradients','format','Boolean');
 			if obj.issmbgradients,
-				WriteData(fid,'object',obj,'fieldname','href','format','DoubleMat','mattype',1);
-				WriteData(fid,'object',obj,'fieldname','smbref','format','DoubleMat','mattype',1);
-				WriteData(fid,'object',obj,'fieldname','b_pos','format','DoubleMat','mattype',1);
-				WriteData(fid,'object',obj,'fieldname','b_neg','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','href','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+				WriteData(fid,'object',obj,'fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+				WriteData(fid,'object',obj,'fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+				WriteData(fid,'object',obj,'fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
 			end
 
Index: /issm/trunk/src/m/classes/surfaceforcings.py
===================================================================
--- /issm/trunk/src/m/classes/surfaceforcings.py	(revision 15395)
+++ /issm/trunk/src/m/classes/surfaceforcings.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -13,22 +12,22 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
-		self.precipitation = float('NaN')
-		self.mass_balance  = float('NaN')
-		self.ispdd = 0
-		self.issmbgradients = 0
-		self.isdelta18o = 0
-		self.href = float('NaN')
-		self.smbref = float('NaN')
-		self.b_pos = float('NaN')
-		self.b_neg = float('NaN')
-		self.monthlytemperatures = float('NaN')
-		self.delta18o = float('NaN')
-		self.delta18o_surface = float('NaN')
-		self.temperatures_presentday = float('NaN')
-		self.temperatures_lgm = float('NaN')
+	def __init__(self): # {{{
+		self.precipitation             = float('NaN')
+		self.mass_balance              = float('NaN')
+		self.ispdd                     = 0
+		self.issmbgradients            = 0
+		self.isdelta18o                = 0
+		self.href                      = float('NaN')
+		self.smbref                    = float('NaN')
+		self.b_pos                     = float('NaN')
+		self.b_neg                     = float('NaN')
+		self.monthlytemperatures       = float('NaN')
+		self.delta18o                  = float('NaN')
+		self.delta18o_surface          = float('NaN')
+		self.temperatures_presentday   = float('NaN')
+		self.temperatures_lgm          = float('NaN')
 		self.precipitations_presentday = float('NaN')
+		self.desfac                    = 0.
+		self.s0p                       = 0.
 
 		#set defaults
@@ -36,6 +35,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string="   surface forcings parameters:"
 
@@ -43,9 +41,11 @@
 		string="%s\n%s"%(string,fielddisplay(self,'mass_balance','surface mass balance [m/yr ice eq]'))
 		string="%s\n%s"%(string,fielddisplay(self,'ispdd','is pdd activated (0 or 1, default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]'))
 		string="%s\n%s"%(string,fielddisplay(self,'isdelta18o','is temperature and precipitation delta18o parametrisation activated (0 or 1, default is 0)'))
-		string="%s\n%s"%(string,fielddisplay(self,'monthlytemperatures','monthly surface temperatures [Kelvin], required if pdd is activated and delta18o not activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'monthlytemperatures','monthly surface temperatures [K], required if pdd is activated and delta18o not activated'))
 		string="%s\n%s"%(string,fielddisplay(self,'precipitation','surface precipitation [m/yr water eq]'))
-		string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [Kelvin], required if pdd is activated and delta18o activated'))
-		string="%s\n%s"%(string,fielddisplay(self,'temperatures_lgm','monthly LGM surface temperatures [Kelvin], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperatures_lgm','monthly LGM surface temperatures [K], required if pdd is activated and delta18o activated'))
 		string="%s\n%s"%(string,fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o activated'))
 		string="%s\n%s"%(string,fielddisplay(self,'delta18o','delta18o, required if pdd is activated and delta18o activated'))
@@ -59,6 +59,5 @@
 		return string
 		#}}}
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		  
 		#pdd method not used in default mode
@@ -66,8 +65,9 @@
 		self.issmbgradients=0
 		self.isdelta18o=0
+		self.desfac=0.5
+		self.s0p=0.
 
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -76,4 +76,6 @@
 			md = checkfield(md,'surfaceforcings.issmbgradients','numel',[1],'values',[0,1])
 			if   self.ispdd:
+				md = checkfield(md,'surfaceforcings.desfac','<=',1,'numel',[1]);
+				md = checkfield(md,'surfaceforcings.s0p','>=',0,'numel',[1]);
 				if not self.isdelta18o:
 					md = checkfield(md,'surfaceforcings.monthlytemperatures','forcing',1,'NaN',1)
@@ -98,12 +100,16 @@
 		return md
 	# }}}
+	def marshall(self,md,fid):    # {{{
 
-	def marshall(self,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','precipitation','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','mass_balance','format','DoubleMat','mattype',1)
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'object',self,'fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
 		WriteData(fid,'object',self,'fieldname','ispdd','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','isdelta18o','format','Boolean')
 
 		if self.ispdd:
+			WriteData(fid,'object',self,'fieldname','desfac','format','Double');
+			WriteData(fid,'object',self,'fieldname','s0p','format','Double');
 			if self.isdelta18o:
 				WriteData(fid,'object',self,'fieldname','temperatures_presentday','format','DoubleMat','mattype',1)
@@ -113,14 +119,12 @@
 				WriteData(fid,'object',self,'fieldname','delta18o','format','DoubleMat','mattype',1)
 			else:
-				WriteData(fid,'object',self,'fieldname','monthlytemperatures','format','DoubleMat','mattype',1)
-				WriteData(fid,'object',self,'fieldname','precipitation','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
 
 		WriteData(fid,'object',self,'fieldname','issmbgradients','format','Boolean')
 
 		if self.issmbgradients:
-			WriteData(fid,'object',self,'fieldname','href','format','DoubleMat','mattype',1)
-			WriteData(fid,'object',self,'fieldname','smbref','format','DoubleMat','mattype',1)
-			WriteData(fid,'object',self,'fieldname','b_pos','format','DoubleMat','mattype',1)
-			WriteData(fid,'object',self,'fieldname','b_neg','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','href','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',self,'fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',self,'fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',self,'fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
 	# }}}
-
Index: /issm/trunk/src/m/classes/taoinversion.m
===================================================================
--- /issm/trunk/src/m/classes/taoinversion.m	(revision 15395)
+++ /issm/trunk/src/m/classes/taoinversion.m	(revision 15396)
@@ -1,3 +1,3 @@
-%INVERSION class definition
+%TAOINVERSION class definition
 %
 %   Usage:
@@ -83,5 +83,5 @@
 			if solution==BalancethicknessSolutionEnum()
 				md = checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
-			elseif solution==WeakBalancethicknessSolutionEnum()
+			elseif solution==BalancethicknessSoftSolutionEnum()
 				md = checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
 			else
@@ -93,6 +93,6 @@
 			disp(sprintf('   taoinversion parameters:'));
 			fielddisplay(obj,'iscontrol','is inversion activated?');
-			fielddisplay(obj,'incomplete_adjoint','do we assume linear viscosity?');
-			fielddisplay(obj,'control_parameters','parameter where inverse control is carried out; ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
 			fielddisplay(obj,'nsteps','number of optimization searches');
 			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
@@ -100,7 +100,7 @@
 			fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
 			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(obj,'vx_obs','observed velocity x component [m/a]');
-			fielddisplay(obj,'vy_obs','observed velocity y component [m/a]');
-			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/a]');
+			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
 			fielddisplay(obj,'thickness_obs','observed thickness [m]');
 			disp('Available cost functions:');
@@ -115,5 +115,5 @@
 			disp('   503: ThicknessAbsGradient');
 		end % }}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 
 			WriteData(fid,'object',obj,'class','inversion','fieldname','iscontrol','format','Boolean');
Index: /issm/trunk/src/m/classes/thermal.m
===================================================================
--- /issm/trunk/src/m/classes/thermal.m	(revision 15395)
+++ /issm/trunk/src/m/classes/thermal.m	(revision 15396)
@@ -57,6 +57,6 @@
 			disp(sprintf('   Thermal solution parameters:'));
 
-			fielddisplay(obj,'spctemperature','temperature constraints (NaN means no constraint)');
-			fielddisplay(obj,'stabilization','0->no, 1->artificial_diffusivity, 2->SUPG');
+			fielddisplay(obj,'spctemperature','temperature constraints (NaN means no constraint) [K]');
+			fielddisplay(obj,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG');
 			fielddisplay(obj,'maxiter','maximum number of non linear iterations');
 			fielddisplay(obj,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
@@ -65,6 +65,6 @@
 
 		end % }}}
-		function marshall(obj,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','spctemperature','format','DoubleMat','mattype',1);
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','spctemperature','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
 			WriteData(fid,'object',obj,'fieldname','penalty_threshold','format','Integer');
 			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
Index: /issm/trunk/src/m/classes/thermal.py
===================================================================
--- /issm/trunk/src/m/classes/thermal.py	(revision 15395)
+++ /issm/trunk/src/m/classes/thermal.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 import numpy
 from fielddisplay import fielddisplay
@@ -14,7 +13,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.spctemperature    = float('NaN')
 		self.penalty_threshold = 0
@@ -29,9 +26,8 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string='   Thermal solution parameters:'
-		string="%s\n%s"%(string,fielddisplay(self,'spctemperature','temperature constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0->no, 1->artificial_diffusivity, 2->SUPG'))
+		string="%s\n%s"%(string,fielddisplay(self,'spctemperature','temperature constraints (NaN means no constraint) [K]'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG'))
 		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of non linear iterations'))
 		string="%s\n%s"%(string,fielddisplay(self,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)'))
@@ -40,7 +36,5 @@
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#Number of unstable constraints acceptable
@@ -61,5 +55,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -78,7 +71,6 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1)
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
 		WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer')
 		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
@@ -88,3 +80,2 @@
 		WriteData(fid,'object',self,'fieldname','isenthalpy','format','Boolean')
 	# }}}
-
Index: /issm/trunk/src/m/classes/timestepping.m
===================================================================
--- /issm/trunk/src/m/classes/timestepping.m	(revision 15395)
+++ /issm/trunk/src/m/classes/timestepping.m	(revision 15396)
@@ -47,15 +47,18 @@
 			disp(sprintf('   timestepping parameters:'));
 
-			fielddisplay(obj,'start_time','simulation starting time [yrs]');
-			fielddisplay(obj,'final_time','final time to stop the simulation [yrs]');
-			fielddisplay(obj,'time_step','length of time steps [yrs]');
+			fielddisplay(obj,'start_time','simulation starting time [yr]');
+			fielddisplay(obj,'final_time','final time to stop the simulation [yr]');
+			fielddisplay(obj,'time_step','length of time steps [yr]');
 			fielddisplay(obj,'time_adapt','use cfl condition to define time step ? (0 or 1) ');
 			fielddisplay(obj,'cfl_coefficient','coefficient applied to cfl condition');
 
 		end % }}}
-		function marshall(obj,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','start_time','format','Double');
-			WriteData(fid,'object',obj,'fieldname','final_time','format','Double');
-			WriteData(fid,'object',obj,'fieldname','time_step','format','Double');
+		function marshall(obj,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',obj,'fieldname','start_time','format','Double','scale',yts);
+			WriteData(fid,'object',obj,'fieldname','final_time','format','Double','scale',yts);
+			WriteData(fid,'object',obj,'fieldname','time_step','format','Double','scale',yts);
 			WriteData(fid,'object',obj,'fieldname','time_adapt','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','cfl_coefficient','format','Double');
Index: /issm/trunk/src/m/classes/timestepping.py
===================================================================
--- /issm/trunk/src/m/classes/timestepping.py	(revision 15395)
+++ /issm/trunk/src/m/classes/timestepping.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -13,7 +12,5 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.start_time      = 0.
 		self.final_time      = 0.
@@ -26,17 +23,14 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	def __repr__(self): # {{{
 		string="   timestepping parameters:"
-		string="%s\n%s"%(string,fielddisplay(self,"start_time","simulation starting time [yrs]"))
-		string="%s\n%s"%(string,fielddisplay(self,"final_time","final time to stop the simulation [yrs]"))
-		string="%s\n%s"%(string,fielddisplay(self,"time_step","length of time steps [yrs]"))
+		string="%s\n%s"%(string,fielddisplay(self,"start_time","simulation starting time [yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"final_time","final time to stop the simulation [yr]"))
+		string="%s\n%s"%(string,fielddisplay(self,"time_step","length of time steps [yr]"))
 		string="%s\n%s"%(string,fielddisplay(self,"time_adapt","use cfl condition to define time step ? (0 or 1) "))
 		string="%s\n%s"%(string,fielddisplay(self,"cfl_coefficient","coefficient applied to cfl condition"))
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#time between 2 time steps
@@ -52,5 +46,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -65,11 +58,12 @@
 		return md
 	# }}}
+	def marshall(self,md,fid):    # {{{
 
-	def marshall(self,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','start_time','format','Double')
-		WriteData(fid,'object',self,'fieldname','final_time','format','Double')
-		WriteData(fid,'object',self,'fieldname','time_step','format','Double')
+		yts=365.0*24.0*3600.0
+
+		WriteData(fid,'object',self,'fieldname','start_time','format','Double','scale',yts)
+		WriteData(fid,'object',self,'fieldname','final_time','format','Double','scale',yts)
+		WriteData(fid,'object',self,'fieldname','time_step','format','Double','scale',yts)
 		WriteData(fid,'object',self,'fieldname','time_adapt','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','cfl_coefficient','format','Double')
 	# }}}
-
Index: /issm/trunk/src/m/classes/toolkits.m
===================================================================
--- /issm/trunk/src/m/classes/toolkits.m	(revision 15396)
+++ /issm/trunk/src/m/classes/toolkits.m	(revision 15396)
@@ -0,0 +1,122 @@
+%TOOLKITS class definition
+%
+%   Usage:
+%      obj=toolkits();
+
+classdef toolkits < dynamicprops
+    properties (SetAccess=public) 
+		 DefaultAnalysis           = struct();
+		 %The other properties are dynamic
+	 end
+	 methods
+		 function obj = toolkits(varargin) % {{{
+			 switch nargin
+				 case 0
+					 obj=setdefaultparameters(obj);
+				 case 1
+					 obj=structtoobj(obj,varargin{1});
+				 otherwise
+					 error('constructor not supported');
+				 end
+			 end % }}}
+		 function obj = addoptions(obj,analysis,varargin) % {{{
+		 % Usage example:
+		 %    md.toolkits=addoptions(md.toolkits,DiagnosticHorizAnalysisEnum(),stokesoptions());
+		 %    md.toolkits=addoptions(md.toolkits,DiagnosticHorizAnalysisEnum());
+
+			 %Convert analysis from enum to string
+			 analysis=EnumToString(analysis);
+
+			 %Create dynamic property if property does not exist yet
+			 if ~ismember(analysis,properties(obj)),
+				 obj.addprop(analysis);
+			 end
+
+			 %Add toolkits options to analysis
+			 if nargin==3, obj.(analysis) = varargin{1}; end
+		 end
+		 %}}}
+		 function obj = setdefaultparameters(obj) % {{{
+
+			 %default toolkits: 
+			 if ispetsc,
+				 %MUMPS is the default toolkits
+				 if ismumps(),
+					 obj.DefaultAnalysis           = mumpsoptions();
+				 else
+					 obj.DefaultAnalysis           = iluasmoptions(); 
+				 end
+			 else
+				 obj.DefaultAnalysis           = issmsolver(); 
+			 end
+
+		 end % }}}
+		 function disp(obj) % {{{
+			 analyses=properties(obj);
+			 disp(sprintf('List of toolkits options per analysis:\n'));
+			 for i=1:numel(analyses),
+				 analysis=analyses{i};
+				 disp([analysis ':']);
+				 disp(obj.(analysis));
+			 end
+		 end % }}}
+		 function md = checkconsistency(obj,md,solution,analyses) % {{{
+			 analyses=properties(obj);
+			 for i=1:numel(analyses),
+				 if isempty(fieldnames(obj.(analyses{i})))
+					 md = checkmessage(md,['md.toolkits.' analyses{i} ' is empty']);
+				 end
+			 end
+		 end % }}}
+		 function ToolkitsFile(toolkits,filename) % {{{
+		 %TOOLKITSFILE - build toolkits file
+		 %
+		 %   Build a Petsc compatible options file, from the toolkits model field  + return options string. 
+		 %   This file will also be used when the toolkit used is 'issm' instead of 'petsc'
+		 %
+		 %   Usage:     ToolkitsFile(toolkits,filename);
+
+			 %open file for writing
+			 fid=fopen(filename,'w');
+			 if fid==-1,
+				 error(['ToolkitsFile error: could not open ' filename ' for writing']);
+			 end
+
+			 %write header
+			 fprintf(fid,'%s%s%s\n','%Toolkits options file: ',filename,' written from Matlab toolkits array');
+
+			 %start writing options
+			 analyses=properties(toolkits);
+			 for i=1:numel(analyses),
+				 analysis=analyses{i};
+				 options=toolkits.(analysis);
+
+				 %first write analysis:
+				 fprintf(fid,'\n+%s\n',analysis); %append a + to recognize it's an analysis enum
+
+				 %now, write options
+				 optionslist=fieldnames(options);
+				 for j=1:numel(optionslist),
+					 optionname=optionslist{j};
+					 optionvalue=options.(optionname);
+
+					 if isempty(optionvalue),
+						 %this option has only one argument
+						 fprintf(fid,'-%s\n',optionname);
+					 else
+						 %option with value. value can be string or scalar
+						 if isnumeric(optionvalue),
+							 fprintf(fid,'-%s %g\n',optionname,optionvalue);
+						 elseif ischar(optionvalue),
+							 fprintf(fid,'-%s %s\n',optionname,optionvalue);
+						 else
+							 error(['ToolkitsFile error: option ' optionname ' is not well formatted']);
+						 end
+					 end
+				 end
+			 end
+
+			 fclose(fid);
+		 end %}}}
+	 end
+ end
Index: /issm/trunk/src/m/classes/toolkits.py
===================================================================
--- /issm/trunk/src/m/classes/toolkits.py	(revision 15396)
+++ /issm/trunk/src/m/classes/toolkits.py	(revision 15396)
@@ -0,0 +1,108 @@
+from ismumps import *
+from ispetsc import *
+from mumpsoptions import *
+from iluasmoptions import *
+from EnumToString import EnumToString
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from MatlabFuncs import *
+
+class toolkits(object):
+	"""
+	TOOLKITS class definition
+
+	   Usage:
+	      obj=toolkits();
+	"""
+
+	def __init__(self):    # {{{
+		#default toolkits
+		if ispetsc():
+			#MUMPS is the default toolkits
+			if ismumps():
+				self.DefaultAnalysis           = mumpsoptions()
+			else:
+				self.DefaultAnalysis           = iluasmoptions()
+		else:
+			self.DefaultAnalysis           = issmsolver()
+
+		#The other properties are dynamic
+	# }}}
+	def __repr__(self):    # {{{
+		s ="List of toolkits options per analysis:\n\n"
+		for analysis in vars(self).iterkeys():
+			s+="%s\n" % fielddisplay(self,analysis,'')
+
+		return s
+	# }}}
+	def addoptions(self,analysis,*args):    # {{{
+		# Usage example:
+		#    md.toolkits=addoptions(md.toolkits,DiagnosticHorizAnalysisEnum(),stokesoptions());
+		#    md.toolkits=addoptions(md.toolkits,DiagnosticHorizAnalysisEnum());
+
+		#Convert analysis from enum to string
+		[analysis]=EnumToString(analysis)
+
+		#Create dynamic property if property does not exist yet
+		if not hasattr(self,analysis):
+#			exec("self.%s = None" % analysis)
+			setattr(self,analysis,None)
+
+		#Add toolkits options to analysis
+		if len(args)==1:
+			setattr(self,analysis,args[0])
+
+		return self
+	# }}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		for analysis in vars(self).iterkeys():
+			if not getattr(self,analysis):
+				md.checkmessage("md.toolkits.%s is empty" % analysis)
+
+		return md
+	# }}}
+	def ToolkitsFile(self,filename):    # {{{
+		"""
+		TOOLKITSFILE- build toolkits file
+
+		   Build a Petsc compatible options file, from the toolkits model field  + return options string
+		   This file will also be used when the toolkit used is 'issm' instead of 'petsc'
+
+
+		   Usage:     ToolkitsFile(toolkits,filename);
+		"""
+
+		#open file for writing
+		try:
+			fid=open(filename,'w')
+		except IOError as e:
+			raise IOError("ToolkitsFile error: could not open '%s' for writing." % filename)
+
+		#write header
+		fid.write("%s%s%s\n" % ('%Petsc options file: ',filename,' written from Matlab toolkits array'))
+
+		#start writing options
+		for analysis in vars(self).iterkeys():
+			options=getattr(self,analysis)
+
+			#first write analysis:
+			fid.write("\n+%s\n" % analysis)    #append a + to recognize it's an analysis enum
+
+			#now, write options
+			for optionname,optionvalue in options.iteritems():
+
+				if not optionvalue:
+					#this option has only one argument
+					fid.write("-%s\n" % optionname)
+				else:
+					#option with value. value can be string or scalar
+					if   isinstance(optionvalue,(bool,int,long,float)):
+						fid.write("-%s %g\n" % (optionname,optionvalue))
+					elif isinstance(optionvalue,(str,unicode)):
+						fid.write("-%s %s\n" % (optionname,optionvalue))
+					else:
+						raise TypeError("ToolkitsFile error: option '%s' is not well formatted." % optionname)
+
+		fid.close()
+	# }}}
Index: /issm/trunk/src/m/classes/transient.m
===================================================================
--- /issm/trunk/src/m/classes/transient.m	(revision 15395)
+++ /issm/trunk/src/m/classes/transient.m	(revision 15396)
@@ -10,4 +10,5 @@
 		isthermal         = 0;
 		isgroundingline   = 0;
+		isgia             = 0;
 		requested_outputs = NaN;
 	end
@@ -28,4 +29,5 @@
 			obj.isthermal=1;
 			obj.isgroundingline=0;
+			obj.isgia=0;
 
 		end % }}}
@@ -39,4 +41,5 @@
 			md = checkfield(md,'transient.isthermal','numel',[1],'values',[0 1]);
 			md = checkfield(md,'transient.isgroundingline','numel',[1],'values',[0 1]);
+			md = checkfield(md,'transient.isgia','numel',[1],'values',[0 1]);
 			md = checkfield(md,'transient.requested_outputs','size',[NaN 1]);
 
@@ -49,12 +52,14 @@
 			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');
+			fielddisplay(obj,'isgia','indicates if a postglacial rebound model is used in the transient');
 			fielddisplay(obj,'requested_outputs','list of additional outputs requested');
 
 		end % }}}
-		function marshall(obj,fid) % {{{
+		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','isthermal','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','isgroundingline','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isgia','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
 		end % }}}
Index: /issm/trunk/src/m/classes/transient.py
===================================================================
--- /issm/trunk/src/m/classes/transient.py	(revision 15395)
+++ /issm/trunk/src/m/classes/transient.py	(revision 15396)
@@ -1,3 +1,2 @@
-#module imports
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -13,11 +12,10 @@
 	"""
 
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self): # {{{
 		self.isprognostic      = False
 		self.isdiagnostic      = False
 		self.isthermal         = False
 		self.isgroundingline   = False
+		self.isgia             = False
 		self.requested_outputs = float('NaN')
 
@@ -26,6 +24,5 @@
 
 		#}}}
-	def __repr__(self):
-		# {{{ Display
+	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'))
@@ -33,10 +30,9 @@
 		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'))
+		string="%s\n%s"%(string,fielddisplay(self,'isgia','indicates if a postglacial rebound is used in the transient'))
 		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','list of additional outputs requested'))
 		return string
 		#}}}
-		
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#full analysis: Diagnostic, Prognostic and Thermal but no groundingline migration for now
@@ -45,8 +41,8 @@
 		self.isthermal=True
 		self.isgroundingline=False
+		self.isgia=False
 
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -59,4 +55,5 @@
 		md = checkfield(md,'transient.isthermal','numel',[1],'values',[0,1])
 		md = checkfield(md,'transient.isgroundingline','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.isgia','numel',[1],'values',[0,1])
 		md = checkfield(md,'transient.requested_outputs','size',[float('NaN')])
 
@@ -64,10 +61,10 @@
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	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','isthermal','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','isgroundingline','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isgia','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
 	# }}}
Index: /issm/trunk/src/m/classes/verbose.m
===================================================================
--- /issm/trunk/src/m/classes/verbose.m	(revision 15395)
+++ /issm/trunk/src/m/classes/verbose.m	(revision 15396)
@@ -41,5 +41,7 @@
 			switch(nargin),
 				case 0,
-					%Don't do anything
+					verbose.solution=true;
+					verbose.qmu=true;
+					verbose.control=true;
 				case 1,
 					binary=varargin{1};
@@ -124,5 +126,5 @@
 		end
 		%}}}
-		function marshall(obj,fid) % {{{
+		function marshall(obj,md,fid) % {{{
 			WriteData(fid,'data',VerboseToBinary(obj),'enum',VerboseEnum(),'format','Integer');
 		end % }}}
Index: /issm/trunk/src/m/classes/verbose.py
===================================================================
--- /issm/trunk/src/m/classes/verbose.py	(revision 15395)
+++ /issm/trunk/src/m/classes/verbose.py	(revision 15396)
@@ -42,4 +42,7 @@
 		if not len(args):
 			#Don't do anything
+			self.solution=True;
+			self.qmu=True;
+			self.control=True;
 			pass
 
@@ -69,5 +72,4 @@
 					raise TypeError("verbose supported field values are logicals only (True or False)")
 	# }}}
-
 	def __repr__(self):    # {{{
 			
@@ -86,5 +88,4 @@
 		return s
 	# }}}
-
 	def VerboseToBinary(self):    # {{{
 
@@ -111,5 +112,4 @@
 		return binary
 	# }}}
-
 	def BinaryToVerbose(self,binary):    # {{{
 
@@ -125,11 +125,8 @@
 		#ENDBIN2VERB
 	# }}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 		return md
 	# }}}
-
-	def marshall(self,fid):    # {{{
+	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'data',self.VerboseToBinary(),'enum',VerboseEnum(),'format','Integer')
 	# }}}
-
Index: /issm/trunk/src/m/consistency/ismodelselfconsistent.m
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 15395)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 15396)
@@ -69,5 +69,5 @@
 		analyses=[BalancethicknessAnalysisEnum()];
 
-	case WeakBalancethicknessSolutionEnum(),
+	case BalancethicknessSoftSolutionEnum(),
 		numanalyses=1; 
 		analyses=[BalancethicknessAnalysisEnum()];
@@ -81,4 +81,8 @@
 		analyses=[BedSlopeAnalysisEnum()];
 
+	case GiaSolutionEnum(),
+		numanalyses=1; 
+		analyses=[GiaAnalysisEnum()];
+
 	case TransientSolutionEnum(),
 		numanalyses=9; 
@@ -91,5 +95,5 @@
 	case HydrologySolutionEnum(),
 		numanalyses=3; 
-		analyses=[BedSlopeAnalysisEnum();SurfaceSlopeAnalysisEnum();HydrologyAnalysisEnum()];
+		analyses=[BedSlopeAnalysisEnum();SurfaceSlopeAnalysisEnum();HydrologyShreveAnalysisEnum();HydrologyDCInefficientAnalysisEnum();HydrologyDCEfficientAnalysisEnum()];
 
 	otherwise
Index: /issm/trunk/src/m/consistency/ismodelselfconsistent.py
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.py	(revision 15395)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.py	(revision 15396)
@@ -42,4 +42,8 @@
 		analyses=[BedSlopeAnalysisEnum()]
 
+	elif solutiontype == GiaSolutionEnum():
+		numanalyses=1
+		analyses=[GiaAnalysisEnum()]
+
 	elif solutiontype == TransientSolutionEnum():
 		numanalyses=9 
@@ -52,5 +56,5 @@
 	elif solutiontype == HydrologySolutionEnum():
 		numanalyses=3 
-		analyses=[BedSlopeAnalysisEnum(),SurfaceSlopeAnalysisEnum(),HydrologyAnalysisEnum()]
+		analyses=[BedSlopeAnalysisEnum(),SurfaceSlopeAnalysisEnum(),HydrologyShreveAnalysisEnum(),HydrologyDCInefficientAnalysisEnum(),HydrologyDCEfficientAnalysisEnum()]
 
 	else:
Index: /issm/trunk/src/m/contrib/gslib/pkriging.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/pkriging.m	(revision 15395)
+++ /issm/trunk/src/m/contrib/gslib/pkriging.m	(revision 15396)
@@ -6,5 +6,5 @@
 
 options=pairoptions(varargin{:});
-cluster=getfieldvalue(options,'cluster',generic('np',10));
+cluster=getfieldvalue(options,'cluster',generic('np',1));
 options=removefield(options,'cluster',0);
 name   = ['krig' num2str(feature('GetPid'))];
@@ -35,8 +35,11 @@
 %Launch job on remote cluster
 BuildKrigingQueueScript(cluster,name,'',1,0,0); %gather, valgrind, gprof
-tic
 LaunchQueueJob(cluster,name,name,{[name '.bin'] [name '.queue']});
-toc
-choice=input('Is the job successfully completed? (y/n)','s');
+
+%Call waitonlock
+md=model; md.cluster=cluster; md.settings.waitonlock=Inf;
+waitonlock(md)
+
+%Download
 Download(cluster,name,{[name '.outbin']});
 structure=parseresultsfromdisk([name '.outbin'],0);
@@ -50,6 +53,6 @@
 
 %Process results
-B=structure.AutodiffForward;
+B=structure.(EnumToString(0));
 B=reshape(B,size(x_interp,2),size(x_interp,1))';
-E=structure.AutodiffIsautodiff;
+E=structure.(EnumToString(1));
 E=reshape(E,size(x_interp,2),size(x_interp,1))';
Index: /issm/trunk/src/m/contrib/massbalance/outflux.m
===================================================================
--- /issm/trunk/src/m/contrib/massbalance/outflux.m	(revision 15396)
+++ /issm/trunk/src/m/contrib/massbalance/outflux.m	(revision 15396)
@@ -0,0 +1,48 @@
+function flux=outflux(md,varargin)
+%OUTFLUX - flag nodes on outflux boundary
+%
+%   Usage:
+%      flag=outflow(md);
+%      flag=outflow(md,step);
+
+A=md.mesh.segments(:,1);
+B=md.mesh.segments(:,2);
+
+lx=-(md.mesh.y(A)-md.mesh.y(B));
+ly=  md.mesh.x(A)-md.mesh.x(B);
+L=sqrt(lx.^2+ly.^2);
+Nx=lx./L;
+Ny=ly./L;
+
+if nargin==1,
+	if md.mesh.dimension==3,
+		vxa=DepthAverage(md,md.initialization.vx);
+		vya=DepthAverage(md,md.initialization.vy);
+	else
+		vxa=md.initialization.vx;
+		vya=md.initialization.vy;
+	end
+	Vx=(vxa(A)+vxa(B))/2;
+	Vy=(vya(A)+vya(B))/2;
+	H=(md.geometry.thickness(A)+md.geometry.thickness(B))/2;
+else
+	step=varargin{1};
+	if md.mesh.dimension==3,
+		vxa=DepthAverage(md,md.results.TransientSolution(step).Vx);
+		vya=DepthAverage(md,md.results.TransientSolution(step).Vy);
+	else
+		vxa=md.results.TransientSolution(step).Vx;
+		vya=md.results.TransientSolution(step).Vy;
+	end
+	Vx=(vxa(A)+vxa(B))/2;
+	Vy=(vya(A)+vya(B))/2;
+	H=(md.results.TransientSolution(step).Thickness(A)+md.results.TransientSolution(step).Thickness(B))/2;
+end
+
+%dot product
+HVdotN=H.*(Vx.*Nx+Vy.*Ny).*L;
+
+%plot_scatter(md.mesh.x(A),md.mesh.y(A),md.materials.rho_ice*HVdotN,'MarkerSize',4);
+flux=md.materials.rho_ice*sum(HVdotN)/10^12;
+
+disp(['Out flux is ' num2str(flux) ' Gt/yr'])
Index: /issm/trunk/src/m/contrib/paraview/writeVTKcell.m
===================================================================
--- /issm/trunk/src/m/contrib/paraview/writeVTKcell.m	(revision 15396)
+++ /issm/trunk/src/m/contrib/paraview/writeVTKcell.m	(revision 15396)
@@ -0,0 +1,122 @@
+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 15396)
+++ /issm/trunk/src/m/coordsystems/lambert2xy.m	(revision 15396)
@@ -0,0 +1,69 @@
+function [x,y] = lambert2xy(lat,lon,sgn,projection_center_lat,projection_center_lon)  
+%LAMBERT2XY - converts lat long from Lambert Azimuthal to Polar Stereographic
+%
+%   Converts from geodetic latitude and longitude that are 
+%   in Lambert Azimuthal (equal area) projections to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%
+%   Usage:
+%      [x,y] = lambert2xy(lat,lon,sgn)
+%      [x,y] = lambert2xy(lat,lon,sgn,projection_center_lat,projection_center_lon)
+%
+%      - provide lat in [-90,90] and lon in [-180,180].
+
+%      - sgn = +1 N hemisphere [default projection center lat = 90 lon=0]
+%              -1 S hemisphere [default projection center lat = -90 lon=0]
+
+%Get projection_center_lat and projection_center_lon 
+if nargin==5,
+	latitude0  = projection_center_lat;
+	longitude0 = projection_center_lon;
+elseif nargin==3,
+	if sgn==1,
+		latitude0 = 90; longitude0 = 0;
+		disp('Info: creating coordinates in polar stereographic (Projection center lat: 90N lon: 0)');
+	elseif sgn==-1,
+		latitude0 = -90; longitude0 = 0;
+		disp('Info: creating coordinates in polar stereographic (Projection center lat: 90S lon: 0)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help lambert2xy
+	error('bad usage');
+end
+
+% Radius of the earth in meters 
+a = 6378137.0;
+% Eccentricity of the Hughes ellipsoid squared
+e = 0.081819191;
+
+% Projection center latitude and longitude in radians 
+phi0 = latitude0 * pi/180; 
+lam0 = longitude0 * pi/180; 
+
+% Some constant based on phi0 and lam0
+qp= (1-e^2)*((1/(1-e^2))-((1/(2*e))*log((1-e)/(1+e))));
+q0=(1-e^2)*((sin(phi0)/(1-e^2*sin(phi0)*sin(phi0)))-((1/(2*e))*log((1-e*sin(phi0))/(1+e*sin(phi0)))));
+Rq=a*sqrt(qp/2);
+b0=asin(q0/qp);
+D =a*(cos(phi0)/sqrt(1-e^2*sin(phi0)*sin(phi0)))/(Rq*cos(b0));
+
+% Latitude and longitude in radians 
+phi = lat*pi/180;
+lam = lon*pi/180;
+
+% Some other phi,lam dependent parameters 
+q=(1-e^2)*((sin(phi)/(1-e^2*sin(phi)*sin(phi)))-((1/(2*e))*log((1-e*sin(phi))/(1+e*sin(phi)))));
+b =asin(q/qp);
+B =Rq*sqrt(2/(1+sin(b0)*sin(b)+(cos(b0)*cos(b)*cos(lam-lam0))));
+
+% Calculation of x and y
+if(abs(lat)==90)
+	x=0.0; 
+	y=0.0; 
+else
+	x=(B*D)*(cos(b)*sin(lam-lam0));
+	y=(B/D)*((cos(b0)*sin(b))-(sin(b0)*cos(b)*cos(lam-lam0)));
+end
+
Index: /issm/trunk/src/m/coordsystems/ll2mercator.m
===================================================================
--- /issm/trunk/src/m/coordsystems/ll2mercator.m	(revision 15396)
+++ /issm/trunk/src/m/coordsystems/ll2mercator.m	(revision 15396)
@@ -0,0 +1,13 @@
+function [mx my]=ll2mercator(lat, lon),
+%LL2MERCATOR - transform lat long to mercator projection
+%
+%   Usage:
+%      [mx my]=ll2mercator(lat, lon)
+
+EARTH_RADIUS = 6378137;
+EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS;
+ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0;
+
+mx = (lon * ORIGIN_SHIFT) / 180.0;
+my = log(tan((90 + lat) * pi/360.0))/(pi/180.0);
+my = (my * ORIGIN_SHIFT) /180.0;
Index: /issm/trunk/src/m/coordsystems/ll2xy.m
===================================================================
--- /issm/trunk/src/m/coordsystems/ll2xy.m	(revision 15396)
+++ /issm/trunk/src/m/coordsystems/ll2xy.m	(revision 15396)
@@ -0,0 +1,66 @@
+function [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)  
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,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 nargin==5,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==3
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help ll2xy
+	error('bad usage');
+end
+
+% 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    =  sqrt(ex2);
+
+latitude  = abs(lat) * pi/180.;
+longitude = (lon + delta) * pi/180.;
+
+% compute X and Y in grid coordinates.
+T = tan(pi/4-latitude/2) ./ ((1-ex*sin(latitude))./(1+ex*sin(latitude))).^(ex/2);
+
+if (90 - slat) <  1.e-5 
+	rho = 2.*re*T/sqrt((1.+ex)^(1.+ex)*(1.-ex)^(1.-ex));
+else
+	sl  = slat*pi/180.;
+	tc  = tan(pi/4.-sl/2.)/((1.-ex*sin(sl))/(1.+ex*sin(sl)))^(ex/2.);
+	mc  = cos(sl)/sqrt(1.0-ex2*(sin(sl)^2));
+	rho = re*mc*T/tc;
+end
+
+y = -rho .* sgn .* cos(sgn.*longitude);
+x =  rho .* sgn .* sin(sgn.*longitude);
+
+[cnt1,cnt2] = find(latitude >= pi / 2.);
+
+if cnt1
+	x(cnt1,1) = 0.0;
+	y(cnt1,1) = 0.0;
+end
Index: /issm/trunk/src/m/coordsystems/mercator2ll.m
===================================================================
--- /issm/trunk/src/m/coordsystems/mercator2ll.m	(revision 15396)
+++ /issm/trunk/src/m/coordsystems/mercator2ll.m	(revision 15396)
@@ -0,0 +1,13 @@
+function [lat lon]=mercator2ll(mx,my),
+%LL2MERCATOR - transform mercator projection to lat/lon
+%
+%   Usage:
+%      [lat lon]=mercator2ll(mx,my)
+
+EARTH_RADIUS = 6378137;
+EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS;
+ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0;
+
+lon = mx * 180.0 / ORIGIN_SHIFT;
+lat = my * 180.0 /ORIGIN_SHIFT;
+lat = 180.0/pi*(2.0*atan(exp(lat*pi/180.0))-pi/2.0);
Index: /issm/trunk/src/m/coordsystems/utm2ll.m
===================================================================
--- /issm/trunk/src/m/coordsystems/utm2ll.m	(revision 15396)
+++ /issm/trunk/src/m/coordsystems/utm2ll.m	(revision 15396)
@@ -0,0 +1,117 @@
+function  [Lat,Lon] = utm2ll(xx,yy,utmzone)
+% -------------------------------------------------------------------------
+% [Lat,Lon] = utm2ll(x,y,utmzone)
+%
+% Description: Function to convert vectors of UTM coordinates into Lat/Lon vectors (WGS84).
+% Some code has been extracted from UTMIP.m function by Gabriel Ruiz Martinez.
+%
+% Inputs:on)
+%    -3.485713    7.801235 -119.955246  -17.759537  -94.799019  121.640266
+%
+% Example 2: If you need Lat/Lon coordinates in Degrees, Minutes and Seconds
+% [Lat, Lon]=utm2ll(x,y,utmzone);
+% LatDMS=dms2mat(deg2dms(Lat))
+%LatDMS =
+%    40.00         18.00         55.55
+%    46.00         17.00          2.01
+%    37.00         34.00         40.17
+%    28.00         38.00         44.33
+%    38.00         51.00         19.96
+%    25.00          3.00         42.41
+% LonDMS=dms2mat(deg2dms(Lon))
+%LonDMS =
+%    -3.00         29.00          8.61
+%     7.00         48.00          4.40
+%  -119.00         57.00         18.93
+%   -17.00         45.00         34.33
+%   -94.00         47.00         56.47
+%   121.00         38.00         24.96
+%
+% Author:
+%   Rafael Palacios
+%   Universidad Pontificia Comillas
+%   Madrid, Spain
+% Version: Apr/06, Jun/06, Aug/06
+% Aug/06: corrected m-Lint warnings
+%-------------------------------------------------------------------------
+
+% Argument checking
+%
+error(nargchk(3, 3, nargin)); %3 arguments required
+n1=length(xx);
+n2=length(yy);
+n3=size(utmzone,1);
+if (n1~=n2 || n1~=n3)
+	error('x,y and utmzone vectors should have the same number or rows');
+end
+c=size(utmzone,2);
+if (c~=4)
+	error('utmzone should be a vector of strings like "30 T"');
+end
+
+% Memory pre-allocation
+%
+Lat=zeros(n1,1);
+Lon=zeros(n1,1);
+
+% Main Loop
+%
+for i=1:n1
+	if (utmzone(i,4)>'X' || utmzone(i,4)<'C')
+		fprintf('utm2ll: Warning utmzone should be a vector of strings like "30 T", not "30 t"\n');
+	end
+	if (utmzone(i,4)>'M')
+		hemis='N';   % Northern hemisphere
+	else
+		hemis='S';
+	end
+
+	x=xx(i);
+	y=yy(i);
+	zone=str2double(utmzone(i,1:2));
+
+	sa = 6378137.000000 ; sb = 6356752.314245;
+
+	%   e = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sa;
+	e2 = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sb;
+	e2cuadrada = e2 ^ 2;
+	c = ( sa ^ 2 ) / sb;
+	%   alpha = ( sa - sb ) / sa;             %f
+	%   ablandamiento = 1 / alpha;   % 1/f
+
+	X = x - 500000;
+
+	if hemis == 'S' || hemis == 's'
+		Y = y - 10000000;
+	else
+		Y = y;
+	end
+
+	S = ( ( zone * 6 ) - 183 );
+	lat =  Y / ( 6366197.724 * 0.9996 );
+	v = ( c / ( ( 1 + ( e2cuadrada * ( cos(lat) ) ^ 2 ) ) ) ^ 0.5 ) * 0.9996;
+	a = X / v;
+	a1 = sin( 2 * lat );
+	a2 = a1 * ( cos(lat) ) ^ 2;
+	j2 = lat + ( a1 / 2 );
+	j4 = ( ( 3 * j2 ) + a2 ) / 4;
+	j6 = ( ( 5 * j4 ) + ( a2 * ( cos(lat) ) ^ 2) ) / 3;
+	alfa = ( 3 / 4 ) * e2cuadrada;
+	beta = ( 5 / 3 ) * alfa ^ 2;
+	gama = ( 35 / 27 ) * alfa ^ 3;
+	Bm = 0.9996 * c * ( lat - alfa * j2 + beta * j4 - gama * j6 );
+	b = ( Y - Bm ) / v;
+	Epsi = ( ( e2cuadrada * a^ 2 ) / 2 ) * ( cos(lat) )^ 2;
+	Eps = a * ( 1 - ( Epsi / 3 ) );
+	nab = ( b * ( 1 - Epsi ) ) + lat;
+	senoheps = ( exp(Eps) - exp(-Eps) ) / 2;
+	Delt = atan(senoheps / (cos(nab) ) );
+	TaO = atan(cos(Delt) * tan(nab));
+	longitude = (Delt *(180 / pi ) ) + S;
+	latitude = ( lat + ( 1 + e2cuadrada* (cos(lat)^ 2) - ( 3 / 2 ) * e2cuadrada * sin(lat) * cos(lat) * ( TaO - lat ) ) * ( TaO - lat ) ) * ...
+		(180 / pi);
+
+	Lat(i)=latitude;
+	Lon(i)=longitude;
+
+end
Index: /issm/trunk/src/m/coordsystems/xy2lambert.m
===================================================================
--- /issm/trunk/src/m/coordsystems/xy2lambert.m	(revision 15396)
+++ /issm/trunk/src/m/coordsystems/xy2lambert.m	(revision 15396)
@@ -0,0 +1,69 @@
+function [lat,lon] = xy2lambert(x,y,sgn,projection_center_lat,projection_center_lon)  
+%XY2LAMBERT - converts xy to lat lon in Lambert Azimuthal
+%
+%   Converts from Ploar Stereographic (X,Y) coordinates to geodetic 
+%   lat lon that are in Lambert Azimuthal (equal area) projection.
+%
+%   Usage:
+%      [lat,lon] = xy2lambert(x,y,sgn)
+%      [lat,lon] = xy2lambert(x,y,sgn,projection_center_lat,projection_center_lon)
+%
+%      - provide lat in [-90,90] and lon in [-180,180].
+%
+%      - sgn = +1 N hemisphere [default projection center lat = 90 lon=0]
+%              -1 S hemisphere [default projection center lat = -90 lon=0]
+
+%Get projection_center_lat and projection_center_lon 
+if nargin==5,
+	latitude0  = projection_center_lat;
+	longitude0 = projection_center_lon;
+elseif nargin==3,
+	if sgn==1,
+		latitude0 = 90; longitude0 = 0;
+		disp('Info: creating coordinates in Lambert Azimuthal equal-area (Projection center lat: 90N lon: 0)');
+	elseif sgn==-1,
+		latitude0 = -90; longitude0 = 0;
+		disp('Info: creating coordinates in Lambert Azimuthal equal-area (Projection center lat: 90S lon: 0)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help xy2lambert
+	error('bad usage');
+end
+
+% Radius of the earth in meters 
+a = 6378137.0;
+% Eccentricity of the Hughes ellipsoid squared
+e = 0.081819191;
+
+% Projection center latitude and longitude in radians 
+phi0 = latitude0 * pi/180; 
+lam0 = longitude0 * pi/180; 
+
+% Some constants based on phi0 and lam0
+% (as in forward calculation)
+qp= (1-e^2)*((1/(1-e^2))-((1/(2*e))*log((1-e)/(1+e))));
+q0=(1-e^2)*((sin(phi0)/(1-e^2*sin(phi0)*sin(phi0)))-((1/(2*e))*log((1-e*sin(phi0))/(1+e*sin(phi0)))));
+Rq=a*sqrt(qp/2);
+b0=asin(q0/qp);
+D =a*(cos(phi0)/sqrt(1-e^2*sin(phi0)*sin(phi0)))/(Rq*cos(b0));
+
+% Some other (x,y) dependent parameters 
+rho=sqrt((x/D)^2+(D*y)^2);
+C=2*asin(rho/(2*Rq));
+b_prime=asin((cos(C)*sin(b0))+((D*y*sin(C)*cos(b0))/rho));
+
+% Calculation of lat and lon 
+dist=sqrt(x^2+y^2);
+if(dist<=0.1)
+	lat=sgn*90.0;
+	lon=0.0;
+else
+	lat_rad=b_prime+((e^2/3+31*e^4/180+517*e^6/5040)*sin(2*b_prime))+((23*e^4/360+251*e^6/3780)*sin(4*b_prime))+((761*e^6/45360)*sin(6*b_prime));
+	lon_rad=lam0+atan(x*sin(C)/(D*rho*cos(b0)*cos(C)-D^2*y*sin(b0)*sin(C)));
+	% in degrees 
+	lat=lat_rad*180/pi;
+	lon=lon_rad*180/pi;
+end
+
Index: /issm/trunk/src/m/coordsystems/xy2ll.m
===================================================================
--- /issm/trunk/src/m/coordsystems/xy2ll.m	(revision 15396)
+++ /issm/trunk/src/m/coordsystems/xy2ll.m	(revision 15396)
@@ -0,0 +1,72 @@
+function [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel)
+%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 nargin==5,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==3
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help xy2ll
+	error('bad usage');
+end
+
+% 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    =  sqrt(ex2);
+
+sl  = slat*pi/180.;
+rho = sqrt(x.^2 + y.^2);
+cm = cos(sl) / sqrt(1.0 - ex2 * (sin(sl)^2));
+T = tan((pi / 4.0) - (sl / 2.0)) / ((1.0 - ex * sin(sl)) / (1.0 + ex * sin(sl)))^(ex / 2.0);
+
+if  abs(slat-90.) < 1.e-5
+	T = rho * sqrt((1. + ex)^(1. + ex) * (1. - ex)^(1. - ex)) / 2. / re;
+else
+	T = rho * T / (re * cm);
+end
+
+chi = (pi / 2.0) - 2.0 * atan(T);
+lat = chi + ((ex2 / 2.0) + (5.0 * ex2^2.0 / 24.0) + (ex2^3.0 / 12.0)) * ...
+	sin(2 * chi) + ((7.0 * ex2^2.0 / 48.0) + (29.0 * ex2^3 / 240.0)) * ...
+	sin(4.0 * chi) + (7.0 * ex2^3.0 / 120.0) * sin(6.0 * chi) ;
+
+lat = sgn * lat;
+lon = atan2(sgn * x,-sgn * y);
+lon = sgn * lon;
+
+[res1,res2] = find(rho <= 0.1);
+if res1
+	lat(res1,1) = 90. * sgn;
+	lon(res1,1) = 0.0;
+end
+
+lon = lon * 180. / pi;
+lat = lat * 180. / pi;
+lon = lon - delta; 
Index: /issm/trunk/src/m/enum/AbsoluteEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AbsoluteEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AbsoluteEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AdjointBalancethicknessAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdjointBalancethicknessAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AdjointBalancethicknessAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AdjointEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdjointEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AdjointEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AdjointHorizAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdjointHorizAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AdjointHorizAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AdjointSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdjointSolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AdjointSolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AdjointpEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdjointpEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AdjointpEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AdjointxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdjointxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AdjointxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AdjointyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdjointyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AdjointyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AdjointzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdjointzEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AdjointzEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AdolcParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdolcParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AdolcParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AgressiveMigrationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AgressiveMigrationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AgressiveMigrationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AirEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AirEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AirEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AnalysisCounterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AnalysisCounterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AnalysisCounterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AnalysisTypeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AnalysisTypeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AnalysisTypeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AndroidFrictionCoefficientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AndroidFrictionCoefficientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AndroidFrictionCoefficientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ApproximationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ApproximationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ArrheniusEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ArrheniusEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ArrheniusEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffDependentObjectIndicesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDependentObjectIndicesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffDependentObjectIndicesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffDependentObjectNamesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDependentObjectNamesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffDependentObjectNamesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffDependentObjectTypesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDependentObjectTypesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffDependentObjectTypesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffDependentObjectsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDependentObjectsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffDependentObjectsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffDriverEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDriverEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffDriverEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffFosForwardIndexEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffFosForwardIndexEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffFosForwardIndexEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffFosReverseIndexEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffFosReverseIndexEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffFosReverseIndexEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffFovForwardIndicesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffFovForwardIndicesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffFovForwardIndicesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffIndependentObjectNamesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffIndependentObjectNamesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffIndependentObjectNamesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffIndependentObjectTypesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffIndependentObjectTypesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffIndependentObjectTypesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffIndependentObjectsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffIndependentObjectsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffIndependentObjectsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffIsautodiffEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffIsautodiffEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffIsautodiffEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffJacobianEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffJacobianEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffJacobianEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffKeepEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffKeepEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffKeepEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffMassFluxSegmentsPresentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffMassFluxSegmentsPresentEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffMassFluxSegmentsPresentEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffNumDependentObjectsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffNumDependentObjectsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffNumDependentObjectsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffNumDependentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffNumDependentsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffNumDependentsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffNumIndependentObjectsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffNumIndependentObjectsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffNumIndependentObjectsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffNumIndependentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffNumIndependentsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffNumIndependentsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/AutodiffXpEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffXpEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/AutodiffXpEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BalancethicknessAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BalancethicknessAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BalancethicknessMisfitEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessMisfitEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BalancethicknessMisfitEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BalancethicknessSoftAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessSoftAnalysisEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/BalancethicknessSoftAnalysisEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('BalancethicknessSoftAnalysis');
Index: /issm/trunk/src/m/enum/BalancethicknessSoftSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessSoftSolutionEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/BalancethicknessSoftSolutionEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('BalancethicknessSoftSolution');
Index: /issm/trunk/src/m/enum/BalancethicknessSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessSolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BalancethicknessSolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BalancethicknessSpcthicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessSpcthicknessEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BalancethicknessSpcthicknessEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BalancethicknessStabilizationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessStabilizationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BalancethicknessStabilizationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BalancethicknessThickeningRateEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessThickeningRateEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BalancethicknessThickeningRateEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BasalFrictionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BasalFrictionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BasalFrictionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BasalforcingsGeothermalfluxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BasalforcingsGeothermalfluxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BasalforcingsGeothermalfluxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BasalforcingsMeltingRateCorrectionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BasalforcingsMeltingRateCorrectionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BasalforcingsMeltingRateCorrectionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BasalforcingsMeltingRateEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BasalforcingsMeltingRateEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BasalforcingsMeltingRateEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BasisIntegralEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BasisIntegralEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/BasisIntegralEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('BasisIntegral');
Index: /issm/trunk/src/m/enum/BathymetryEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BathymetryEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BathymetryEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BedEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BedEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BedEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BedSlopeAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BedSlopeAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BedSlopeAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BedSlopeSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BedSlopeSolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BedSlopeSolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BedSlopeXAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BedSlopeXAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BedSlopeXAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BedSlopeXEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BedSlopeXEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BedSlopeXEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BedSlopeYAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BedSlopeYAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BedSlopeYAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BedSlopeYEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BedSlopeYEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BedSlopeYEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BilinearInterpEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BilinearInterpEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BilinearInterpEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BoolElementResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BoolElementResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BoolElementResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BoolExternalResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BoolExternalResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BoolExternalResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BoolInputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BoolInputEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BoolInputEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BoolParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BoolParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BoolParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/BoundaryEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BoundaryEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/BoundaryEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ClosedEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ClosedEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ClosedEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ColinearEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ColinearEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ColinearEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ConfigurationTypeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ConfigurationTypeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ConfigurationTypeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ConstantEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ConstantEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ConstantEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ConstantsGEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ConstantsGEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ConstantsGEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ConstantsReferencetemperatureEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ConstantsReferencetemperatureEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ConstantsReferencetemperatureEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ConstantsYtsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ConstantsYtsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ConstantsYtsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ConstraintsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ConstraintsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ConstraintsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ContourEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ContourEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ContourEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ContoursEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ContoursEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/ContoursEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('Contours');
Index: /issm/trunk/src/m/enum/ControlInputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ControlInputEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ControlInputEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ControlSteadyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ControlSteadyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ControlSteadyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ConvergedEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ConvergedEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ConvergedEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DataSetParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DataSetParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DataSetParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DatasetInputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DatasetInputEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DatasetInputEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DebugProfilingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DebugProfilingEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DebugProfilingEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DefaultAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DefaultAnalysisEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/DefaultAnalysisEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('DefaultAnalysis');
Index: /issm/trunk/src/m/enum/DenseEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DenseEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/DenseEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('Dense');
Index: /issm/trunk/src/m/enum/DependentObjectEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DependentObjectEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DependentObjectEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticAbstolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticAbstolEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticAbstolEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticHorizAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticHorizAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticHorizAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticHutterAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticHutterAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticHutterAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticIcefrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticIcefrontEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticIcefrontEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticIsnewtonEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticIsnewtonEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticIsnewtonEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticMaxiterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticMaxiterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticMaxiterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticNumRequestedOutputsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticNumRequestedOutputsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticPenaltyFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticPenaltyFactorEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticPenaltyFactorEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticReferentialEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticReferentialEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticReferentialEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticReltolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticReltolEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticReltolEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticRequestedOutputsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticRequestedOutputsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticRestolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticRestolEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticRestolEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticRiftPenaltyLockEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticRiftPenaltyLockEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticRiftPenaltyLockEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticRiftPenaltyThresholdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticRiftPenaltyThresholdEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticRiftPenaltyThresholdEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticShelfDampeningEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticShelfDampeningEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticShelfDampeningEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticSolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticSolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticSpcvxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticSpcvxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticSpcvxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticSpcvyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticSpcvyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticSpcvyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticSpcvzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticSpcvzEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticSpcvzEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticStokesreconditioningEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticStokesreconditioningEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticStokesreconditioningEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticVertAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticVertAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticVertAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticVertexPairingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticVertexPairingEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticVertexPairingEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DiagnosticViscosityOvershootEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticViscosityOvershootEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DiagnosticViscosityOvershootEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DofIndexingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DofIndexingEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DofIndexingEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DoubleElementResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DoubleElementResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DoubleElementResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DoubleExternalResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DoubleExternalResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DoubleExternalResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DoubleInputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DoubleInputEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DoubleInputEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DoubleMatArrayParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DoubleMatArrayParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DoubleMatArrayParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DoubleMatExternalResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DoubleMatExternalResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DoubleMatExternalResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DoubleMatParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DoubleMatParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DoubleMatParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DoubleParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DoubleParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DoubleParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/DoubleVecExternalResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DoubleVecExternalResultEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DoubleVecExternalResultEnum()
-%DOUBLEVECEXTERNALRESULTENUM - Enum of DoubleVecExternalResult
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=DoubleVecExternalResultEnum()
-
-macro=StringToEnum('DoubleVecExternalResult');
Index: /issm/trunk/src/m/enum/DoubleVecParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DoubleVecParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DoubleVecParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/DragCoefficientAbsGradientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DragCoefficientAbsGradientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/DragCoefficientAbsGradientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ElementEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ElementEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ElementEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ElementResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ElementResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ElementResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/EnthalpyAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/EnthalpyAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/EnthalpyAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/EnthalpyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/EnthalpyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/EnthalpyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/EnthalpyPicardEnum.m
===================================================================
--- /issm/trunk/src/m/enum/EnthalpyPicardEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/EnthalpyPicardEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/EnthalpySolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/EnthalpySolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/EnthalpySolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/EnumDefinitions.py
===================================================================
--- /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 15395)
+++ /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 15396)
@@ -4,6 +4,6 @@
 
    WARNING: DO NOT MODIFY THIS FILE
-            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-            Please read src/c/EnumDefinitions/README for more information
+            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+            Please read src/c/shared/Enum/README for more information
 
 """
@@ -13,4 +13,8 @@
 	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()
@@ -23,4 +27,8 @@
 	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()
@@ -33,4 +41,8 @@
 	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()
@@ -43,4 +55,8 @@
 	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()
@@ -53,4 +69,8 @@
 	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()
@@ -63,4 +83,8 @@
 	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()
@@ -73,4 +97,8 @@
 	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()
@@ -83,4 +111,8 @@
 	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()
@@ -93,4 +125,8 @@
 	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()
@@ -103,4 +139,8 @@
 	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()
@@ -113,4 +153,8 @@
 	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()
@@ -123,4 +167,8 @@
 	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()
@@ -133,4 +181,8 @@
 	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()
@@ -143,4 +195,8 @@
 	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()
@@ -153,4 +209,8 @@
 	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()
@@ -163,4 +223,8 @@
 	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()
@@ -173,4 +237,8 @@
 	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()
@@ -183,4 +251,8 @@
 	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()
@@ -193,4 +265,8 @@
 	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()
@@ -203,4 +279,8 @@
 	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()
@@ -213,4 +293,8 @@
 	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()
@@ -223,4 +307,8 @@
 	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()
@@ -233,4 +321,8 @@
 	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()
@@ -243,4 +335,8 @@
 	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()
@@ -253,4 +349,8 @@
 	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()
@@ -263,4 +363,8 @@
 	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()
@@ -273,4 +377,8 @@
 	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()
@@ -283,4 +391,8 @@
 	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()
@@ -293,4 +405,8 @@
 	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()
@@ -303,4 +419,8 @@
 	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()
@@ -313,4 +433,8 @@
 	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()
@@ -323,4 +447,8 @@
 	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()
@@ -333,4 +461,8 @@
 	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()
@@ -343,4 +475,8 @@
 	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()
@@ -353,4 +489,8 @@
 	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()
@@ -363,4 +503,8 @@
 	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()
@@ -373,4 +517,8 @@
 	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()
@@ -383,4 +531,8 @@
 	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()
@@ -393,4 +545,8 @@
 	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()
@@ -403,4 +559,8 @@
 	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()
@@ -413,4 +573,8 @@
 	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()
@@ -423,4 +587,8 @@
 	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()
@@ -433,4 +601,8 @@
 	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()
@@ -443,4 +615,8 @@
 	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()
@@ -453,4 +629,8 @@
 	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()
@@ -463,4 +643,8 @@
 	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()
@@ -473,4 +657,8 @@
 	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()
@@ -483,4 +671,8 @@
 	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()
@@ -493,4 +685,8 @@
 	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()
@@ -503,4 +699,8 @@
 	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()
@@ -513,4 +713,8 @@
 	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()
@@ -519,8 +723,54 @@
 	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()
@@ -533,4 +783,8 @@
 	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()
@@ -543,4 +797,8 @@
 	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()
@@ -553,4 +811,8 @@
 	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()
@@ -563,4 +825,8 @@
 	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()
@@ -573,4 +839,8 @@
 	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()
@@ -583,4 +853,8 @@
 	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()
@@ -593,4 +867,8 @@
 	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()
@@ -603,4 +881,8 @@
 	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()
@@ -613,4 +895,8 @@
 	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()
@@ -623,4 +909,8 @@
 	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()
@@ -633,4 +923,8 @@
 	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()
@@ -643,4 +937,8 @@
 	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()
@@ -649,73 +947,563 @@
 	return StringToEnum('GeometryHydrostaticRatio')[0]
 
-def HydrologyCREnum():
-	"""
-	HYDROLOGYCRENUM - Enum of HydrologyCR
-
-	   Usage:
-	      macro=HydrologyCREnum()
-	"""
-
-	return StringToEnum('HydrologyCR')[0]
-
-def HydrologyKnEnum():
-	"""
-	HYDROLOGYKNENUM - Enum of HydrologyKn
-
-	   Usage:
-	      macro=HydrologyKnEnum()
-	"""
-
-	return StringToEnum('HydrologyKn')[0]
-
-def HydrologyNEnum():
-	"""
-	HYDROLOGYNENUM - Enum of HydrologyN
-
-	   Usage:
-	      macro=HydrologyNEnum()
-	"""
-
-	return StringToEnum('HydrologyN')[0]
-
-def HydrologyPEnum():
-	"""
-	HYDROLOGYPENUM - Enum of HydrologyP
-
-	   Usage:
-	      macro=HydrologyPEnum()
-	"""
-
-	return StringToEnum('HydrologyP')[0]
-
-def HydrologyQEnum():
-	"""
-	HYDROLOGYQENUM - Enum of HydrologyQ
-
-	   Usage:
-	      macro=HydrologyQEnum()
-	"""
-
-	return StringToEnum('HydrologyQ')[0]
-
-def HydrologySpcwatercolumnEnum():
-	"""
-	HYDROLOGYSPCWATERCOLUMNENUM - Enum of HydrologySpcwatercolumn
-
-	   Usage:
-	      macro=HydrologySpcwatercolumnEnum()
-	"""
-
-	return StringToEnum('HydrologySpcwatercolumn')[0]
-
-def HydrologyStabilizationEnum():
-	"""
-	HYDROLOGYSTABILIZATIONENUM - Enum of HydrologyStabilization
-
-	   Usage:
-	      macro=HydrologyStabilizationEnum()
-	"""
-
-	return StringToEnum('HydrologyStabilization')[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():
@@ -723,4 +1511,8 @@
 	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()
@@ -733,4 +1525,8 @@
 	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()
@@ -739,18 +1535,12 @@
 	return StringToEnum('InversionControlParameters')[0]
 
-def InversionCostFunctionEnum():
-	"""
-	INVERSIONCOSTFUNCTIONENUM - Enum of InversionCostFunction
-
-	   Usage:
-	      macro=InversionCostFunctionEnum()
-	"""
-
-	return StringToEnum('InversionCostFunction')[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()
@@ -763,4 +1553,8 @@
 	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()
@@ -773,4 +1567,8 @@
 	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()
@@ -783,4 +1581,8 @@
 	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()
@@ -793,4 +1595,8 @@
 	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()
@@ -803,4 +1609,8 @@
 	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()
@@ -813,4 +1623,8 @@
 	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()
@@ -823,4 +1637,8 @@
 	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()
@@ -833,4 +1651,8 @@
 	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()
@@ -843,4 +1665,8 @@
 	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()
@@ -853,4 +1679,8 @@
 	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()
@@ -863,4 +1693,8 @@
 	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()
@@ -873,4 +1707,8 @@
 	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()
@@ -883,4 +1721,8 @@
 	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()
@@ -893,4 +1735,8 @@
 	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()
@@ -903,4 +1749,8 @@
 	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()
@@ -913,4 +1763,8 @@
 	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()
@@ -923,4 +1777,8 @@
 	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()
@@ -933,4 +1791,8 @@
 	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()
@@ -943,4 +1805,8 @@
 	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()
@@ -953,4 +1819,8 @@
 	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()
@@ -963,4 +1833,8 @@
 	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()
@@ -973,4 +1847,8 @@
 	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()
@@ -983,4 +1861,8 @@
 	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()
@@ -993,4 +1875,8 @@
 	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()
@@ -1003,4 +1889,8 @@
 	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()
@@ -1013,4 +1903,8 @@
 	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()
@@ -1023,4 +1917,8 @@
 	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()
@@ -1033,4 +1931,8 @@
 	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()
@@ -1043,4 +1945,8 @@
 	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()
@@ -1053,4 +1959,8 @@
 	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()
@@ -1063,4 +1973,8 @@
 	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()
@@ -1073,4 +1987,8 @@
 	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()
@@ -1083,4 +2001,8 @@
 	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()
@@ -1093,4 +2015,8 @@
 	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()
@@ -1103,4 +2029,8 @@
 	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()
@@ -1113,4 +2043,8 @@
 	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()
@@ -1123,4 +2057,8 @@
 	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()
@@ -1133,4 +2071,8 @@
 	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()
@@ -1143,4 +2085,8 @@
 	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()
@@ -1153,4 +2099,8 @@
 	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()
@@ -1163,4 +2113,8 @@
 	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()
@@ -1173,4 +2127,8 @@
 	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()
@@ -1179,8 +2137,68 @@
 	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()
@@ -1193,4 +2211,8 @@
 	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()
@@ -1203,4 +2225,8 @@
 	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()
@@ -1213,4 +2239,8 @@
 	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()
@@ -1223,4 +2253,8 @@
 	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()
@@ -1233,4 +2267,8 @@
 	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()
@@ -1243,4 +2281,8 @@
 	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()
@@ -1253,4 +2295,8 @@
 	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()
@@ -1263,4 +2309,8 @@
 	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()
@@ -1273,4 +2323,8 @@
 	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()
@@ -1283,4 +2337,8 @@
 	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()
@@ -1293,4 +2351,8 @@
 	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()
@@ -1303,4 +2365,8 @@
 	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()
@@ -1313,4 +2379,8 @@
 	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()
@@ -1323,4 +2393,8 @@
 	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()
@@ -1333,4 +2407,8 @@
 	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()
@@ -1343,4 +2421,8 @@
 	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()
@@ -1353,4 +2435,8 @@
 	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()
@@ -1363,4 +2449,8 @@
 	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()
@@ -1373,4 +2463,8 @@
 	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()
@@ -1383,4 +2477,8 @@
 	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()
@@ -1393,4 +2491,8 @@
 	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()
@@ -1403,4 +2505,8 @@
 	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()
@@ -1413,4 +2519,8 @@
 	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()
@@ -1423,4 +2533,8 @@
 	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()
@@ -1433,4 +2547,8 @@
 	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()
@@ -1443,4 +2561,8 @@
 	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()
@@ -1453,4 +2575,8 @@
 	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()
@@ -1463,4 +2589,8 @@
 	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()
@@ -1473,4 +2603,8 @@
 	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()
@@ -1483,4 +2617,8 @@
 	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()
@@ -1493,4 +2631,8 @@
 	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()
@@ -1503,4 +2645,8 @@
 	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()
@@ -1513,4 +2659,8 @@
 	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()
@@ -1523,4 +2673,8 @@
 	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()
@@ -1533,4 +2687,8 @@
 	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()
@@ -1543,4 +2701,8 @@
 	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()
@@ -1553,4 +2715,8 @@
 	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()
@@ -1563,4 +2729,8 @@
 	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()
@@ -1569,8 +2739,26 @@
 	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()
@@ -1583,4 +2771,8 @@
 	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()
@@ -1593,4 +2785,8 @@
 	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()
@@ -1603,4 +2799,8 @@
 	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()
@@ -1613,4 +2813,8 @@
 	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()
@@ -1623,4 +2827,8 @@
 	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()
@@ -1633,4 +2841,8 @@
 	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()
@@ -1643,4 +2855,8 @@
 	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()
@@ -1653,4 +2869,8 @@
 	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()
@@ -1663,4 +2883,8 @@
 	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()
@@ -1673,4 +2897,8 @@
 	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()
@@ -1683,4 +2911,8 @@
 	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()
@@ -1693,4 +2925,8 @@
 	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()
@@ -1703,4 +2939,8 @@
 	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()
@@ -1713,4 +2953,8 @@
 	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()
@@ -1723,4 +2967,8 @@
 	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()
@@ -1733,4 +2981,8 @@
 	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()
@@ -1743,4 +2995,8 @@
 	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()
@@ -1753,4 +3009,8 @@
 	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()
@@ -1763,4 +3023,8 @@
 	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()
@@ -1773,4 +3037,8 @@
 	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()
@@ -1783,4 +3051,8 @@
 	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()
@@ -1793,4 +3065,8 @@
 	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()
@@ -1803,4 +3079,8 @@
 	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()
@@ -1813,4 +3093,8 @@
 	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()
@@ -1823,4 +3107,8 @@
 	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()
@@ -1829,8 +3117,40 @@
 	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()
@@ -1843,4 +3163,8 @@
 	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()
@@ -1853,4 +3177,8 @@
 	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()
@@ -1863,4 +3191,8 @@
 	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()
@@ -1873,4 +3205,8 @@
 	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()
@@ -1883,4 +3219,8 @@
 	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()
@@ -1893,4 +3233,8 @@
 	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()
@@ -1903,4 +3247,8 @@
 	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()
@@ -1913,4 +3261,8 @@
 	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()
@@ -1923,4 +3275,8 @@
 	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()
@@ -1933,4 +3289,8 @@
 	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()
@@ -1943,4 +3303,8 @@
 	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()
@@ -1953,4 +3317,8 @@
 	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()
@@ -1959,8 +3327,40 @@
 	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()
@@ -1973,4 +3373,8 @@
 	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()
@@ -1983,4 +3387,8 @@
 	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()
@@ -1993,4 +3401,8 @@
 	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()
@@ -2003,4 +3415,8 @@
 	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()
@@ -2013,4 +3429,8 @@
 	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()
@@ -2023,4 +3443,8 @@
 	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()
@@ -2033,4 +3457,8 @@
 	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()
@@ -2043,4 +3471,8 @@
 	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()
@@ -2053,4 +3485,8 @@
 	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()
@@ -2059,8 +3495,26 @@
 	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()
@@ -2073,4 +3527,8 @@
 	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()
@@ -2083,4 +3541,8 @@
 	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()
@@ -2093,4 +3555,8 @@
 	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()
@@ -2103,4 +3569,8 @@
 	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()
@@ -2113,4 +3583,8 @@
 	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()
@@ -2123,4 +3597,8 @@
 	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()
@@ -2133,4 +3611,8 @@
 	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()
@@ -2143,4 +3625,8 @@
 	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()
@@ -2149,8 +3635,40 @@
 	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()
@@ -2163,4 +3681,8 @@
 	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()
@@ -2169,23 +3691,31 @@
 	return StringToEnum('BalancethicknessSolution')[0]
 
-def WeakBalancethicknessAnalysisEnum():
-	"""
-	WEAKBALANCETHICKNESSANALYSISENUM - Enum of WeakBalancethicknessAnalysis
-
-	   Usage:
-	      macro=WeakBalancethicknessAnalysisEnum()
-	"""
-
-	return StringToEnum('WeakBalancethicknessAnalysis')[0]
-
-def WeakBalancethicknessSolutionEnum():
-	"""
-	WEAKBALANCETHICKNESSSOLUTIONENUM - Enum of WeakBalancethicknessSolution
-
-	   Usage:
-	      macro=WeakBalancethicknessSolutionEnum()
-	"""
-
-	return StringToEnum('WeakBalancethicknessSolution')[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():
@@ -2193,4 +3723,8 @@
 	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()
@@ -2203,4 +3737,8 @@
 	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()
@@ -2213,4 +3751,8 @@
 	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()
@@ -2223,4 +3765,8 @@
 	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()
@@ -2233,4 +3779,8 @@
 	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()
@@ -2243,4 +3793,8 @@
 	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()
@@ -2253,4 +3807,8 @@
 	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()
@@ -2263,4 +3821,8 @@
 	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()
@@ -2273,4 +3835,8 @@
 	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()
@@ -2283,4 +3849,8 @@
 	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()
@@ -2293,4 +3863,8 @@
 	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()
@@ -2303,4 +3877,8 @@
 	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()
@@ -2309,13 +3887,45 @@
 	return StringToEnum('FlaimSolution')[0]
 
-def HydrologyAnalysisEnum():
-	"""
-	HYDROLOGYANALYSISENUM - Enum of HydrologyAnalysis
-
-	   Usage:
-	      macro=HydrologyAnalysisEnum()
-	"""
-
-	return StringToEnum('HydrologyAnalysis')[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():
@@ -2323,4 +3933,8 @@
 	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()
@@ -2333,4 +3947,8 @@
 	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()
@@ -2339,18 +3957,12 @@
 	return StringToEnum('MeltingAnalysis')[0]
 
-def NoneAnalysisEnum():
-	"""
-	NONEANALYSISENUM - Enum of NoneAnalysis
-
-	   Usage:
-	      macro=NoneAnalysisEnum()
-	"""
-
-	return StringToEnum('NoneAnalysis')[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()
@@ -2363,4 +3975,8 @@
 	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()
@@ -2373,4 +3989,8 @@
 	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()
@@ -2383,4 +4003,8 @@
 	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()
@@ -2393,4 +4017,8 @@
 	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()
@@ -2403,4 +4031,8 @@
 	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()
@@ -2413,4 +4045,8 @@
 	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()
@@ -2423,4 +4059,8 @@
 	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()
@@ -2433,4 +4073,8 @@
 	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()
@@ -2443,4 +4087,8 @@
 	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()
@@ -2449,8 +4097,40 @@
 	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()
@@ -2463,4 +4143,8 @@
 	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()
@@ -2473,4 +4157,8 @@
 	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()
@@ -2483,4 +4171,8 @@
 	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()
@@ -2493,4 +4185,8 @@
 	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()
@@ -2503,4 +4199,8 @@
 	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()
@@ -2513,4 +4213,8 @@
 	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()
@@ -2523,4 +4227,8 @@
 	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()
@@ -2533,4 +4241,8 @@
 	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()
@@ -2543,4 +4255,8 @@
 	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()
@@ -2553,4 +4269,8 @@
 	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()
@@ -2563,4 +4283,8 @@
 	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()
@@ -2573,4 +4297,8 @@
 	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()
@@ -2583,4 +4311,8 @@
 	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()
@@ -2589,8 +4321,26 @@
 	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()
@@ -2603,4 +4353,8 @@
 	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()
@@ -2613,4 +4367,8 @@
 	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()
@@ -2623,4 +4381,8 @@
 	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()
@@ -2633,4 +4395,8 @@
 	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()
@@ -2643,4 +4409,8 @@
 	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()
@@ -2653,4 +4423,8 @@
 	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()
@@ -2663,4 +4437,8 @@
 	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()
@@ -2673,4 +4451,8 @@
 	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()
@@ -2683,4 +4465,8 @@
 	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()
@@ -2693,4 +4479,8 @@
 	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()
@@ -2703,4 +4493,8 @@
 	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()
@@ -2713,4 +4507,8 @@
 	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()
@@ -2723,4 +4521,8 @@
 	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()
@@ -2733,4 +4535,8 @@
 	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()
@@ -2743,4 +4549,8 @@
 	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()
@@ -2753,4 +4563,8 @@
 	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()
@@ -2763,4 +4577,8 @@
 	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()
@@ -2773,4 +4591,8 @@
 	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()
@@ -2783,4 +4605,8 @@
 	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()
@@ -2793,4 +4619,8 @@
 	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()
@@ -2803,4 +4633,8 @@
 	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()
@@ -2813,4 +4647,8 @@
 	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()
@@ -2823,4 +4661,8 @@
 	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()
@@ -2833,4 +4675,8 @@
 	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()
@@ -2843,4 +4689,8 @@
 	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()
@@ -2853,4 +4703,8 @@
 	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()
@@ -2863,4 +4717,8 @@
 	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()
@@ -2869,8 +4727,26 @@
 	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()
@@ -2883,4 +4759,8 @@
 	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()
@@ -2893,4 +4773,8 @@
 	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()
@@ -2903,4 +4787,8 @@
 	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()
@@ -2913,4 +4801,8 @@
 	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()
@@ -2923,4 +4815,8 @@
 	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()
@@ -2933,4 +4829,8 @@
 	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()
@@ -2939,8 +4839,26 @@
 	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()
@@ -2953,4 +4871,8 @@
 	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()
@@ -2963,4 +4885,8 @@
 	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()
@@ -2973,4 +4899,8 @@
 	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()
@@ -2983,4 +4913,8 @@
 	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()
@@ -2993,4 +4927,8 @@
 	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()
@@ -3003,4 +4941,8 @@
 	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()
@@ -3013,4 +4955,8 @@
 	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()
@@ -3023,4 +4969,8 @@
 	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()
@@ -3029,8 +4979,26 @@
 	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()
@@ -3043,4 +5011,8 @@
 	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()
@@ -3049,8 +5021,26 @@
 	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()
@@ -3063,4 +5053,8 @@
 	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()
@@ -3073,4 +5067,8 @@
 	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()
@@ -3083,4 +5081,8 @@
 	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()
@@ -3093,4 +5095,8 @@
 	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()
@@ -3103,4 +5109,8 @@
 	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()
@@ -3113,4 +5123,8 @@
 	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()
@@ -3123,4 +5137,8 @@
 	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()
@@ -3133,4 +5151,8 @@
 	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()
@@ -3139,13 +5161,17 @@
 	return StringToEnum('Tria')[0]
 
-def TriaP1InputEnum():
-	"""
-	TRIAP1INPUTENUM - Enum of TriaP1Input
-
-	   Usage:
-	      macro=TriaP1InputEnum()
-	"""
-
-	return StringToEnum('TriaP1Input')[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():
@@ -3153,4 +5179,8 @@
 	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()
@@ -3159,8 +5189,40 @@
 	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()
@@ -3173,4 +5235,8 @@
 	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()
@@ -3183,4 +5249,8 @@
 	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()
@@ -3193,4 +5263,8 @@
 	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()
@@ -3203,4 +5277,8 @@
 	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()
@@ -3213,4 +5291,8 @@
 	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()
@@ -3223,4 +5305,8 @@
 	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()
@@ -3233,4 +5319,8 @@
 	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()
@@ -3243,4 +5333,8 @@
 	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()
@@ -3253,4 +5347,8 @@
 	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()
@@ -3263,4 +5361,8 @@
 	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()
@@ -3273,4 +5375,8 @@
 	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()
@@ -3283,4 +5389,8 @@
 	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()
@@ -3293,4 +5403,8 @@
 	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()
@@ -3303,4 +5417,8 @@
 	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()
@@ -3313,4 +5431,8 @@
 	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()
@@ -3323,4 +5445,8 @@
 	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()
@@ -3329,18 +5455,12 @@
 	return StringToEnum('Converged')[0]
 
-def ExtToIuEnum():
-	"""
-	EXTTOIUENUM - Enum of ExtToIu
-
-	   Usage:
-	      macro=ExtToIuEnum()
-	"""
-
-	return StringToEnum('ExtToIu')[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()
@@ -3353,4 +5473,8 @@
 	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()
@@ -3363,4 +5487,8 @@
 	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()
@@ -3373,4 +5501,8 @@
 	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()
@@ -3383,4 +5515,8 @@
 	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()
@@ -3389,18 +5525,12 @@
 	return StringToEnum('Internal')[0]
 
-def IuToExtEnum():
-	"""
-	IUTOEXTENUM - Enum of IuToExt
-
-	   Usage:
-	      macro=IuToExtEnum()
-	"""
-
-	return StringToEnum('IuToExt')[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()
@@ -3413,4 +5543,8 @@
 	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()
@@ -3423,4 +5557,8 @@
 	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()
@@ -3433,4 +5571,8 @@
 	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()
@@ -3443,4 +5585,8 @@
 	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()
@@ -3453,4 +5599,8 @@
 	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()
@@ -3463,4 +5613,8 @@
 	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()
@@ -3473,4 +5627,8 @@
 	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()
@@ -3483,4 +5641,8 @@
 	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()
@@ -3493,4 +5655,8 @@
 	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()
@@ -3503,4 +5669,8 @@
 	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()
@@ -3513,4 +5683,8 @@
 	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()
@@ -3523,4 +5697,8 @@
 	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()
@@ -3533,4 +5711,8 @@
 	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()
@@ -3543,4 +5725,8 @@
 	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()
@@ -3549,8 +5735,54 @@
 	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()
@@ -3563,4 +5795,8 @@
 	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()
@@ -3573,4 +5809,8 @@
 	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()
@@ -3583,4 +5823,8 @@
 	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()
@@ -3593,4 +5837,8 @@
 	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()
@@ -3603,4 +5851,8 @@
 	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()
@@ -3613,4 +5865,8 @@
 	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()
@@ -3623,4 +5879,8 @@
 	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()
@@ -3633,4 +5893,8 @@
 	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()
@@ -3643,4 +5907,8 @@
 	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()
@@ -3653,4 +5921,8 @@
 	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()
@@ -3663,4 +5935,8 @@
 	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()
@@ -3673,4 +5949,8 @@
 	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()
@@ -3683,4 +5963,8 @@
 	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()
@@ -3689,28 +5973,12 @@
 	return StringToEnum('TemperaturePicard')[0]
 
-def TemperatureSurfaceEnum():
-	"""
-	TEMPERATURESURFACEENUM - Enum of TemperatureSurface
-
-	   Usage:
-	      macro=TemperatureSurfaceEnum()
-	"""
-
-	return StringToEnum('TemperatureSurface')[0]
-
-def TemperatureBasalEnum():
-	"""
-	TEMPERATUREBASALENUM - Enum of TemperatureBasal
-
-	   Usage:
-	      macro=TemperatureBasalEnum()
-	"""
-
-	return StringToEnum('TemperatureBasal')[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()
@@ -3719,18 +5987,12 @@
 	return StringToEnum('ThicknessAbsMisfit')[0]
 
-def TypeEnum():
-	"""
-	TYPEENUM - Enum of Type
-
-	   Usage:
-	      macro=TypeEnum()
-	"""
-
-	return StringToEnum('Type')[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()
@@ -3743,4 +6005,8 @@
 	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()
@@ -3753,4 +6019,8 @@
 	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()
@@ -3763,4 +6033,8 @@
 	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()
@@ -3773,4 +6047,8 @@
 	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()
@@ -3783,4 +6061,8 @@
 	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()
@@ -3793,4 +6075,8 @@
 	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()
@@ -3803,4 +6089,8 @@
 	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()
@@ -3813,4 +6103,8 @@
 	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()
@@ -3823,4 +6117,8 @@
 	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()
@@ -3833,4 +6131,8 @@
 	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()
@@ -3843,4 +6145,8 @@
 	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()
@@ -3853,4 +6159,8 @@
 	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()
@@ -3863,4 +6173,8 @@
 	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()
@@ -3873,4 +6187,8 @@
 	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()
@@ -3883,4 +6201,8 @@
 	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()
@@ -3893,4 +6215,8 @@
 	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()
@@ -3903,4 +6229,8 @@
 	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()
@@ -3913,4 +6243,8 @@
 	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()
@@ -3923,4 +6257,8 @@
 	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()
@@ -3933,4 +6271,8 @@
 	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()
@@ -3943,4 +6285,8 @@
 	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()
@@ -3953,4 +6299,8 @@
 	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()
@@ -3963,4 +6313,8 @@
 	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()
@@ -3973,4 +6327,8 @@
 	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()
@@ -3983,4 +6341,8 @@
 	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()
@@ -3993,4 +6355,8 @@
 	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()
@@ -4003,4 +6369,8 @@
 	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()
@@ -4013,4 +6383,8 @@
 	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()
@@ -4023,4 +6397,8 @@
 	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()
@@ -4033,4 +6411,8 @@
 	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()
@@ -4043,4 +6425,8 @@
 	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()
@@ -4053,4 +6439,8 @@
 	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()
@@ -4063,4 +6453,8 @@
 	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()
@@ -4073,4 +6467,8 @@
 	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()
@@ -4083,4 +6481,8 @@
 	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()
@@ -4093,4 +6495,8 @@
 	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()
@@ -4103,4 +6509,8 @@
 	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()
@@ -4113,4 +6523,8 @@
 	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()
@@ -4123,4 +6537,8 @@
 	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()
@@ -4129,8 +6547,54 @@
 	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()
@@ -4143,4 +6607,8 @@
 	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()
@@ -4153,4 +6621,8 @@
 	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()
@@ -4159,8 +6631,40 @@
 	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()
@@ -4173,4 +6677,8 @@
 	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()
@@ -4183,4 +6691,8 @@
 	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()
@@ -4193,4 +6705,8 @@
 	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()
@@ -4203,4 +6719,8 @@
 	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()
@@ -4213,4 +6733,8 @@
 	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()
@@ -4219,18 +6743,12 @@
 	return StringToEnum('DoubleMatExternalResult')[0]
 
-def DoubleVecExternalResultEnum():
-	"""
-	DOUBLEVECEXTERNALRESULTENUM - Enum of DoubleVecExternalResult
-
-	   Usage:
-	      macro=DoubleVecExternalResultEnum()
-	"""
-
-	return StringToEnum('DoubleVecExternalResult')[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()
@@ -4243,4 +6761,8 @@
 	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()
@@ -4253,4 +6775,8 @@
 	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()
@@ -4263,4 +6789,8 @@
 	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()
@@ -4273,4 +6803,8 @@
 	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()
@@ -4283,4 +6817,8 @@
 	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()
@@ -4289,18 +6827,12 @@
 	return StringToEnum('PentaP1ElementResult')[0]
 
-def PetscVecExternalResultEnum():
-	"""
-	PETSCVECEXTERNALRESULTENUM - Enum of PetscVecExternalResult
-
-	   Usage:
-	      macro=PetscVecExternalResultEnum()
-	"""
-
-	return StringToEnum('PetscVecExternalResult')[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()
@@ -4313,4 +6845,8 @@
 	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()
@@ -4323,4 +6859,8 @@
 	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()
@@ -4333,4 +6873,8 @@
 	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()
@@ -4343,4 +6887,8 @@
 	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()
@@ -4353,4 +6901,8 @@
 	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()
@@ -4363,4 +6915,8 @@
 	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()
@@ -4373,4 +6929,8 @@
 	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()
@@ -4383,4 +6943,8 @@
 	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()
@@ -4393,4 +6957,8 @@
 	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()
@@ -4403,4 +6971,8 @@
 	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()
@@ -4413,4 +6985,8 @@
 	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()
@@ -4423,4 +6999,8 @@
 	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()
@@ -4433,4 +7013,8 @@
 	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()
@@ -4443,4 +7027,8 @@
 	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()
@@ -4453,4 +7041,8 @@
 	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()
@@ -4463,4 +7055,8 @@
 	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()
@@ -4473,4 +7069,8 @@
 	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()
@@ -4479,18 +7079,12 @@
 	return StringToEnum('TotalSmb')[0]
 
-def RelativeEnum():
-	"""
-	RELATIVEENUM - Enum of Relative
-
-	   Usage:
-	      macro=RelativeEnum()
-	"""
-
-	return StringToEnum('Relative')[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()
@@ -4503,4 +7097,8 @@
 	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()
@@ -4513,4 +7111,8 @@
 	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()
@@ -4523,4 +7125,8 @@
 	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()
@@ -4533,4 +7139,8 @@
 	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()
@@ -4539,8 +7149,54 @@
 	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()
@@ -4553,4 +7209,8 @@
 	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()
@@ -4563,4 +7223,8 @@
 	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()
@@ -4573,4 +7237,8 @@
 	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()
@@ -4583,4 +7251,8 @@
 	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()
@@ -4593,4 +7265,8 @@
 	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()
@@ -4603,4 +7279,8 @@
 	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()
@@ -4613,4 +7293,8 @@
 	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()
@@ -4623,4 +7307,8 @@
 	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()
@@ -4633,4 +7321,8 @@
 	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()
@@ -4643,4 +7335,8 @@
 	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()
@@ -4653,4 +7349,8 @@
 	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()
@@ -4663,4 +7363,8 @@
 	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()
@@ -4673,4 +7377,8 @@
 	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()
@@ -4683,4 +7391,8 @@
 	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()
@@ -4693,4 +7405,8 @@
 	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()
@@ -4703,4 +7419,8 @@
 	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()
@@ -4713,4 +7433,8 @@
 	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()
@@ -4723,4 +7447,8 @@
 	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()
@@ -4729,23 +7457,31 @@
 	return StringToEnum('LockFileName')[0]
 
-def PetscOptionsAnalysesEnum():
-	"""
-	PETSCOPTIONSANALYSESENUM - Enum of PetscOptionsAnalyses
-
-	   Usage:
-	      macro=PetscOptionsAnalysesEnum()
-	"""
-
-	return StringToEnum('PetscOptionsAnalyses')[0]
-
-def PetscOptionsStringsEnum():
-	"""
-	PETSCOPTIONSSTRINGSENUM - Enum of PetscOptionsStrings
-
-	   Usage:
-	      macro=PetscOptionsStringsEnum()
-	"""
-
-	return StringToEnum('PetscOptionsStrings')[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():
@@ -4753,4 +7489,8 @@
 	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()
@@ -4763,4 +7503,8 @@
 	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()
@@ -4773,4 +7517,8 @@
 	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()
@@ -4783,4 +7531,8 @@
 	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()
@@ -4793,4 +7545,8 @@
 	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()
@@ -4803,4 +7559,8 @@
 	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()
@@ -4813,4 +7573,8 @@
 	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()
@@ -4823,4 +7587,8 @@
 	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()
@@ -4833,4 +7601,8 @@
 	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()
@@ -4843,4 +7615,8 @@
 	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()
@@ -4853,4 +7629,8 @@
 	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()
@@ -4863,4 +7643,8 @@
 	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()
@@ -4873,4 +7657,8 @@
 	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()
@@ -4879,8 +7667,68 @@
 	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()
@@ -4893,4 +7741,8 @@
 	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()
@@ -4903,4 +7755,8 @@
 	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()
@@ -4913,4 +7769,8 @@
 	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()
@@ -4923,4 +7783,8 @@
 	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()
@@ -4933,4 +7797,8 @@
 	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()
@@ -4943,4 +7811,8 @@
 	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()
@@ -4953,4 +7825,8 @@
 	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()
@@ -4963,4 +7839,8 @@
 	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()
@@ -4973,8 +7853,12 @@
 	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 496
-
+	return 560
+
Index: /issm/trunk/src/m/enum/EplHeadEnum.m
===================================================================
--- /issm/trunk/src/m/enum/EplHeadEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/EplHeadEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('EplHead');
Index: /issm/trunk/src/m/enum/EplHeadOldEnum.m
===================================================================
--- /issm/trunk/src/m/enum/EplHeadOldEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/EplHeadOldEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('EplHeadOld');
Index: sm/trunk/src/m/enum/ExtToIuEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ExtToIuEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=ExtToIuEnum()
-%EXTTOIUENUM - Enum of ExtToIu
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=ExtToIuEnum()
-
-macro=StringToEnum('ExtToIu');
Index: /issm/trunk/src/m/enum/ExternalResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ExternalResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ExternalResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FileParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FileParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FileParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FillEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FillEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FillEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlaimAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlaimAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlaimAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlaimSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlaimSolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlaimSolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlowequationBordermacayealEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationBordermacayealEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlowequationBordermacayealEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlowequationBorderpattynEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationBorderpattynEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlowequationBorderpattynEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlowequationBorderstokesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationBorderstokesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlowequationBorderstokesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlowequationElementEquationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationElementEquationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlowequationElementEquationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlowequationIshutterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIshutterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlowequationIshutterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlowequationIsl1l2Enum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsl1l2Enum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlowequationIsl1l2Enum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlowequationIsmacayealpattynEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsmacayealpattynEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlowequationIsmacayealpattynEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlowequationIsstokesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsstokesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlowequationIsstokesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FlowequationVertexEquationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationVertexEquationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FlowequationVertexEquationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FractionIncrementEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FractionIncrementEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FractionIncrementEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FreeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FreeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FreeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FrictionCoefficientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FrictionCoefficientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FrictionCoefficientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FrictionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FrictionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FrictionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FrictionPEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FrictionPEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FrictionPEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FrictionQEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FrictionQEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FrictionQEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/FsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FsetEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/FsetEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/GLlevelsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GLlevelsetEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/GLlevelsetEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+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/GenericOptionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GenericOptionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/GenericOptionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/GenericParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GenericParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/GenericParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/GeometryHydrostaticRatioEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GeometryHydrostaticRatioEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/GeometryHydrostaticRatioEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/GiaAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GiaAnalysisEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/GiaAnalysisEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('GiaAnalysis');
Index: /issm/trunk/src/m/enum/GiaCrossSectionShapeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GiaCrossSectionShapeEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/GiaCrossSectionShapeEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('GiaCrossSectionShape');
Index: /issm/trunk/src/m/enum/GiaLithosphereThicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GiaLithosphereThicknessEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/GiaLithosphereThicknessEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('GiaLithosphereThickness');
Index: /issm/trunk/src/m/enum/GiaMantleViscosityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GiaMantleViscosityEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/GiaMantleViscosityEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('GiaMantleViscosity');
Index: /issm/trunk/src/m/enum/GiaSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GiaSolutionEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/GiaSolutionEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('GiaSolution');
Index: /issm/trunk/src/m/enum/GiaWEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GiaWEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/GiaWEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('GiaW');
Index: /issm/trunk/src/m/enum/GiadWdtEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GiadWdtEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/GiadWdtEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('GiadWdt');
Index: /issm/trunk/src/m/enum/Gradient1Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Gradient1Enum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/Gradient1Enum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/Gradient2Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Gradient2Enum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/Gradient2Enum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/Gradient3Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Gradient3Enum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/Gradient3Enum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/GradientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GradientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/GradientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/GroundinglineMeltingRateEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GroundinglineMeltingRateEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/GroundinglineMeltingRateEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/GroundinglineMigrationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GroundinglineMigrationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/GroundinglineMigrationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/GsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GsetEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/GsetEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/HookEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HookEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/HookEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/HutterApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HutterApproximationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/HutterApproximationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/HydrologyAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyAnalysisEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HydrologyAnalysisEnum()
-%HYDROLOGYANALYSISENUM - Enum of HydrologyAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=HydrologyAnalysisEnum()
-
-macro=StringToEnum('HydrologyAnalysis');
Index: sm/trunk/src/m/enum/HydrologyCREnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyCREnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HydrologyCREnum()
-%HYDROLOGYCRENUM - Enum of HydrologyCR
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=HydrologyCREnum()
-
-macro=StringToEnum('HydrologyCR');
Index: /issm/trunk/src/m/enum/HydrologyDCEfficientAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyDCEfficientAnalysisEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyDCEfficientAnalysisEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyDCEfficientAnalysis');
Index: /issm/trunk/src/m/enum/HydrologyDCInefficientAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyDCInefficientAnalysisEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyDCInefficientAnalysisEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyDCInefficientAnalysis');
Index: /issm/trunk/src/m/enum/HydrologyEfficientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyEfficientEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyEfficientEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyEfficient');
Index: sm/trunk/src/m/enum/HydrologyKnEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyKnEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HydrologyKnEnum()
-%HYDROLOGYKNENUM - Enum of HydrologyKn
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=HydrologyKnEnum()
-
-macro=StringToEnum('HydrologyKn');
Index: /issm/trunk/src/m/enum/HydrologyLayerEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyLayerEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyLayerEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyLayer');
Index: /issm/trunk/src/m/enum/HydrologyModelEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyModelEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyModelEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyModel');
Index: sm/trunk/src/m/enum/HydrologyNEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyNEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HydrologyNEnum()
-%HYDROLOGYNENUM - Enum of HydrologyN
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=HydrologyNEnum()
-
-macro=StringToEnum('HydrologyN');
Index: sm/trunk/src/m/enum/HydrologyPEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyPEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HydrologyPEnum()
-%HYDROLOGYPENUM - Enum of HydrologyP
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=HydrologyPEnum()
-
-macro=StringToEnum('HydrologyP');
Index: sm/trunk/src/m/enum/HydrologyQEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyQEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HydrologyQEnum()
-%HYDROLOGYQENUM - Enum of HydrologyQ
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=HydrologyQEnum()
-
-macro=StringToEnum('HydrologyQ');
Index: /issm/trunk/src/m/enum/HydrologySedimentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologySedimentEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologySedimentEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologySediment');
Index: /issm/trunk/src/m/enum/HydrologySedimentKmaxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologySedimentKmaxEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologySedimentKmaxEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologySedimentKmax');
Index: /issm/trunk/src/m/enum/HydrologyShreveAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyShreveAnalysisEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyShreveAnalysisEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyShreveAnalysis');
Index: /issm/trunk/src/m/enum/HydrologySolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologySolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/HydrologySolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/HydrologySpcwatercolumnEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologySpcwatercolumnEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HydrologySpcwatercolumnEnum()
-%HYDROLOGYSPCWATERCOLUMNENUM - Enum of HydrologySpcwatercolumn
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=HydrologySpcwatercolumnEnum()
-
-macro=StringToEnum('HydrologySpcwatercolumn');
Index: sm/trunk/src/m/enum/HydrologyStabilizationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyStabilizationEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HydrologyStabilizationEnum()
-%HYDROLOGYSTABILIZATIONENUM - Enum of HydrologyStabilization
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=HydrologyStabilizationEnum()
-
-macro=StringToEnum('HydrologyStabilization');
Index: /issm/trunk/src/m/enum/HydrologyWaterVxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyWaterVxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/HydrologyWaterVxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/HydrologyWaterVyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyWaterVyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/HydrologyWaterVyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/HydrologydcEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('Hydrologydc');
Index: /issm/trunk/src/m/enum/HydrologydcEplCompressibilityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcEplCompressibilityEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcEplCompressibilityEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcEplCompressibility');
Index: /issm/trunk/src/m/enum/HydrologydcEplPorosityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcEplPorosityEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcEplPorosityEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcEplPorosity');
Index: /issm/trunk/src/m/enum/HydrologydcEplThicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcEplThicknessEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcEplThicknessEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcEplThickness');
Index: /issm/trunk/src/m/enum/HydrologydcEplTransmitivityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcEplTransmitivityEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcEplTransmitivityEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcEplTransmitivity');
Index: /issm/trunk/src/m/enum/HydrologydcIsefficientlayerEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcIsefficientlayerEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcIsefficientlayerEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcIsefficientlayer');
Index: /issm/trunk/src/m/enum/HydrologydcLeakageFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcLeakageFactorEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcLeakageFactorEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcLeakageFactor');
Index: /issm/trunk/src/m/enum/HydrologydcMaskEplactiveEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcMaskEplactiveEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcMaskEplactiveEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcMaskEplactive');
Index: /issm/trunk/src/m/enum/HydrologydcPenaltyFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcPenaltyFactorEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcPenaltyFactorEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcPenaltyFactor');
Index: /issm/trunk/src/m/enum/HydrologydcRelTolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcRelTolEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcRelTolEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcRelTol');
Index: /issm/trunk/src/m/enum/HydrologydcSedimentCompressibilityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcSedimentCompressibilityEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcSedimentCompressibilityEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcSedimentCompressibility');
Index: /issm/trunk/src/m/enum/HydrologydcSedimentPorosityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcSedimentPorosityEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcSedimentPorosityEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcSedimentPorosity');
Index: /issm/trunk/src/m/enum/HydrologydcSedimentThicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcSedimentThicknessEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcSedimentThicknessEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcSedimentThickness');
Index: /issm/trunk/src/m/enum/HydrologydcSedimentTransmitivityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcSedimentTransmitivityEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcSedimentTransmitivityEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcSedimentTransmitivity');
Index: /issm/trunk/src/m/enum/HydrologydcSedimentlimitEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcSedimentlimitEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcSedimentlimitEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcSedimentlimit');
Index: /issm/trunk/src/m/enum/HydrologydcSedimentlimitFlagEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcSedimentlimitFlagEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcSedimentlimitFlagEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcSedimentlimitFlag');
Index: /issm/trunk/src/m/enum/HydrologydcSpceplHeadEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcSpceplHeadEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcSpceplHeadEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcSpceplHead');
Index: /issm/trunk/src/m/enum/HydrologydcSpcsedimentHeadEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcSpcsedimentHeadEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcSpcsedimentHeadEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcSpcsedimentHead');
Index: /issm/trunk/src/m/enum/HydrologydcTransferFlagEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcTransferFlagEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcTransferFlagEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcTransferFlag');
Index: /issm/trunk/src/m/enum/HydrologydcWaterCompressibilityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcWaterCompressibilityEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologydcWaterCompressibilityEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologydcWaterCompressibility');
Index: /issm/trunk/src/m/enum/HydrologyshreveCREnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyshreveCREnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyshreveCREnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyshreveCR');
Index: /issm/trunk/src/m/enum/HydrologyshreveEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyshreveEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyshreveEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('Hydrologyshreve');
Index: /issm/trunk/src/m/enum/HydrologyshreveKnEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyshreveKnEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyshreveKnEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyshreveKn');
Index: /issm/trunk/src/m/enum/HydrologyshreveNEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyshreveNEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyshreveNEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyshreveN');
Index: /issm/trunk/src/m/enum/HydrologyshrevePEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyshrevePEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyshrevePEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyshreveP');
Index: /issm/trunk/src/m/enum/HydrologyshreveQEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyshreveQEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyshreveQEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyshreveQ');
Index: /issm/trunk/src/m/enum/HydrologyshreveSpcwatercolumnEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyshreveSpcwatercolumnEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyshreveSpcwatercolumnEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyshreveSpcwatercolumn');
Index: /issm/trunk/src/m/enum/HydrologyshreveStabilizationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologyshreveStabilizationEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/HydrologyshreveStabilizationEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('HydrologyshreveStabilization');
Index: /issm/trunk/src/m/enum/IceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IceFrontTypeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IceFrontTypeEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/IceFrontTypeEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('IceFrontType');
Index: /issm/trunk/src/m/enum/IceVolumeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IceVolumeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IceVolumeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IcefrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IcefrontEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IcefrontEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IncrementalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IncrementalEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IncrementalEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IndependentObjectEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IndependentObjectEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IndependentObjectEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IndexEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IndexEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IndexEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IndexedEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IndexedEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IndexedEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InputEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InputEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IntExternalResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IntExternalResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IntExternalResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IntInputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IntInputEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IntInputEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IntMatParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IntMatParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IntMatParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IntParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IntParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IntParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IntVecParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IntVecParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IntVecParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InternalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InternalEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InternalEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/IntersectEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IntersectEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/IntersectEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionControlParametersEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionControlParametersEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionControlParametersEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/InversionCostFunctionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionCostFunctionEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=InversionCostFunctionEnum()
-%INVERSIONCOSTFUNCTIONENUM - Enum of InversionCostFunction
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=InversionCostFunctionEnum()
-
-macro=StringToEnum('InversionCostFunction');
Index: /issm/trunk/src/m/enum/InversionCostFunctionThresholdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionCostFunctionThresholdEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionCostFunctionThresholdEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionCostFunctionsCoefficientsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionCostFunctionsCoefficientsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionCostFunctionsCoefficientsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionCostFunctionsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionCostFunctionsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionCostFunctionsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionGradientOnlyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionGradientOnlyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionGradientOnlyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionGradientScalingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionGradientScalingEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionGradientScalingEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionIncompleteAdjointEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionIncompleteAdjointEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionIncompleteAdjointEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionIscontrolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionIscontrolEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionIscontrolEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionMaxParametersEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionMaxParametersEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionMaxParametersEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionMaxiterPerStepEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionMaxiterPerStepEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionMaxiterPerStepEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionMinParametersEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionMinParametersEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionMinParametersEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionNstepsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionNstepsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionNstepsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionNumControlParametersEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionNumControlParametersEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionNumControlParametersEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionNumCostFunctionsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionNumCostFunctionsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionNumCostFunctionsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionStepThresholdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionStepThresholdEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionStepThresholdEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionTaoEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionTaoEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionTaoEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionThicknessObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionThicknessObsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionThicknessObsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionVelObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionVelObsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionVelObsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionVxObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionVxObsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionVxObsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionVyObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionVyObsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionVyObsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/InversionVzObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionVzObsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/InversionVzObsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/IuToExtEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IuToExtEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=IuToExtEnum()
-%IUTOEXTENUM - Enum of IuToExt
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=IuToExtEnum()
-
-macro=StringToEnum('IuToExt');
Index: /issm/trunk/src/m/enum/JEnum.m
===================================================================
--- /issm/trunk/src/m/enum/JEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/JEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/L1L2ApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/L1L2ApproximationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/L1L2ApproximationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/L1L2IceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/L1L2IceFrontEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/L1L2IceFrontEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/LoadingforceXEnum.m
===================================================================
--- /issm/trunk/src/m/enum/LoadingforceXEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/LoadingforceXEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('LoadingforceX');
Index: /issm/trunk/src/m/enum/LoadingforceYEnum.m
===================================================================
--- /issm/trunk/src/m/enum/LoadingforceYEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/LoadingforceYEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('LoadingforceY');
Index: /issm/trunk/src/m/enum/LoadingforceZEnum.m
===================================================================
--- /issm/trunk/src/m/enum/LoadingforceZEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/LoadingforceZEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('LoadingforceZ');
Index: /issm/trunk/src/m/enum/LoadsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/LoadsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/LoadsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/LockFileNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/LockFileNameEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/LockFileNameEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MINIEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MINIEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/MINIEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('MINI');
Index: /issm/trunk/src/m/enum/MacAyeal2dIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MacAyeal2dIceFrontEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MacAyeal2dIceFrontEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MacAyeal3dIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MacAyeal3dIceFrontEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MacAyeal3dIceFrontEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MacAyealApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MacAyealApproximationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MacAyealApproximationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MacAyealPattynApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MacAyealPattynApproximationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MacAyealPattynApproximationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MacAyealStokesApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MacAyealStokesApproximationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MacAyealStokesApproximationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaskElementonfloatingiceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskElementonfloatingiceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaskElementonfloatingiceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaskElementongroundediceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskElementongroundediceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaskElementongroundediceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaskElementonwaterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskElementonwaterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaskElementonwaterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaskVertexonfloatingiceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskVertexonfloatingiceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaskVertexonfloatingiceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaskVertexongroundediceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskVertexongroundediceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaskVertexongroundediceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaskVertexonwaterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskVertexonwaterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaskVertexonwaterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MassFluxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassFluxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MassFluxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MassFluxSegmentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassFluxSegmentsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MassFluxSegmentsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MassFluxSegmentsPresentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassFluxSegmentsPresentEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MassFluxSegmentsPresentEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MatdamageiceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MatdamageiceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MatdamageiceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsBetaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsBetaEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsBetaEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsHeatcapacityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsHeatcapacityEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsHeatcapacityEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsLatentheatEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsLatentheatEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsLatentheatEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsLithosphereDensityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsLithosphereDensityEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/MaterialsLithosphereDensityEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('MaterialsLithosphereDensity');
Index: /issm/trunk/src/m/enum/MaterialsLithosphereShearModulusEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsLithosphereShearModulusEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/MaterialsLithosphereShearModulusEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('MaterialsLithosphereShearModulus');
Index: /issm/trunk/src/m/enum/MaterialsMantleDensityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsMantleDensityEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/MaterialsMantleDensityEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('MaterialsMantleDensity');
Index: /issm/trunk/src/m/enum/MaterialsMantleShearModulusEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsMantleShearModulusEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/MaterialsMantleShearModulusEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('MaterialsMantleShearModulus');
Index: /issm/trunk/src/m/enum/MaterialsMeltingpointEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsMeltingpointEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsMeltingpointEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsMixedLayerCapacityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsMixedLayerCapacityEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsMixedLayerCapacityEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsMuWaterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsMuWaterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsMuWaterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsRheologyBEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRheologyBEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsRheologyBEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsRheologyBbarEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRheologyBbarEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsRheologyBbarEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsRheologyLawEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRheologyLawEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsRheologyLawEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsRheologyNEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRheologyNEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsRheologyNEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsRheologyZEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRheologyZEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsRheologyZEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsRheologyZbarEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRheologyZbarEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsRheologyZbarEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsRhoFreshwaterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRhoFreshwaterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsRhoFreshwaterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsRhoIceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRhoIceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsRhoIceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsRhoWaterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRhoWaterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsRhoWaterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsThermalExchangeVelocityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsThermalExchangeVelocityEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsThermalExchangeVelocityEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaterialsThermalconductivityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsThermalconductivityEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaterialsThermalconductivityEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaticeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaticeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaticeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MatparEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MatparEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MatparEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MatrixParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MatrixParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MatrixParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaxAbsVxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxAbsVxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaxAbsVxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaxAbsVyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxAbsVyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaxAbsVyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaxAbsVzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxAbsVzEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaxAbsVzEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaxIterationConvergenceFlagEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxIterationConvergenceFlagEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaxIterationConvergenceFlagEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaxPenetrationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxPenetrationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaxPenetrationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaxVelEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxVelEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaxVelEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaxVxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxVxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaxVxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaxVyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxVyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaxVyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaxVzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxVzEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaxVzEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MaximumNumberOfEnums.m
===================================================================
--- /issm/trunk/src/m/enum/MaximumNumberOfEnums.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MaximumNumberOfEnums.m	(revision 15396)
@@ -3,9 +3,9 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this 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=496;
+macro=560;
Index: /issm/trunk/src/m/enum/MelangeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MelangeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MelangeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeltingAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeltingAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeltingAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeltingOffsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeltingOffsetEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeltingOffsetEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshAverageVertexConnectivityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshAverageVertexConnectivityEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshAverageVertexConnectivityEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshDimensionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshDimensionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshDimensionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshEdgesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshEdgesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshEdgesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshElementconnectivityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshElementconnectivityEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshElementconnectivityEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshElementonbedEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshElementonbedEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshElementonbedEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshElementonsurfaceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshElementonsurfaceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshElementonsurfaceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshElements2dEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshElements2dEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshElements2dEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshElementsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshElementsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshElementsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshLowerelementsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshLowerelementsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshLowerelementsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshNumberofedgesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshNumberofedgesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshNumberofedgesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshNumberofelements2dEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshNumberofelements2dEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshNumberofelements2dEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshNumberofelementsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshNumberofelementsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshNumberofelementsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshNumberoflayersEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshNumberoflayersEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshNumberoflayersEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshNumberofvertices2dEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshNumberofvertices2dEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshNumberofvertices2dEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshNumberofverticesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshNumberofverticesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshNumberofverticesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshUpperelementsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshUpperelementsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshUpperelementsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshVertexonbedEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshVertexonbedEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshVertexonbedEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshVertexonsurfaceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshVertexonsurfaceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshVertexonsurfaceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshXEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshXEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshXEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshYEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshYEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshYEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MeshZEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshZEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MeshZEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MinVelEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MinVelEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MinVelEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MinVxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MinVxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MinVxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MinVyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MinVyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MinVyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MinVzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MinVzEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MinVzEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MiscellaneousNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MiscellaneousNameEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MiscellaneousNameEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MisfitEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MisfitEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/MisfitEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/MpiDenseEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MpiDenseEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/MpiDenseEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('MpiDense');
Index: /issm/trunk/src/m/enum/MpiEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MpiEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/MpiEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('Mpi');
Index: /issm/trunk/src/m/enum/NearestInterpEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NearestInterpEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/NearestInterpEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/NodalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NodalEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/NodalEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/NodeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NodeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/NodeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/NodeSIdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NodeSIdEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/NodeSIdEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('NodeSId');
Index: /issm/trunk/src/m/enum/NodesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NodesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/NodesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/NoneAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NoneAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/NoneAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/NoneApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NoneApproximationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/NoneApproximationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/NoneEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NoneEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/NoneEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/NumberNodeToElementConnectivityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NumberNodeToElementConnectivityEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/NumberNodeToElementConnectivityEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/NumericalfluxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NumericalfluxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/NumericalfluxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/NumericalfluxTypeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/NumericalfluxTypeEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/NumericalfluxTypeEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('NumericalfluxType');
Index: /issm/trunk/src/m/enum/OldGradientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OldGradientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/OldGradientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/OpenEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OpenEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/OpenEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/OptionCellEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OptionCellEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/OptionCellEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/OptionCharEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OptionCharEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/OptionCharEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/OptionDoubleEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OptionDoubleEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/OptionDoubleEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/OptionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OptionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/OptionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/OptionLogicalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OptionLogicalEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/OptionLogicalEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/OptionStructEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OptionStructEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/OptionStructEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/OutputFileNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OutputFileNameEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/OutputFileNameEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/OutputFilePointerEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OutputFilePointerEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/OutputFilePointerEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/P0Enum.m
===================================================================
--- /issm/trunk/src/m/enum/P0Enum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/P0Enum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/P1DGEnum.m
===================================================================
--- /issm/trunk/src/m/enum/P1DGEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/P1DGEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/P1Enum.m
===================================================================
--- /issm/trunk/src/m/enum/P1Enum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/P1Enum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/P2Enum.m
===================================================================
--- /issm/trunk/src/m/enum/P2Enum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/P2Enum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('P2');
Index: /issm/trunk/src/m/enum/ParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ParametersEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ParametersEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ParametersEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PatchEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PatchEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PatchEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PatchNodesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PatchNodesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PatchNodesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PatchVerticesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PatchVerticesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PatchVerticesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PatersonEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PatersonEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PatersonEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PattynApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PattynApproximationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PattynApproximationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PattynIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PattynIceFrontEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PattynIceFrontEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PattynStokesApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PattynStokesApproximationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PattynStokesApproximationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PengridEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PengridEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PengridEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PenpairEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PenpairEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PenpairEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PentaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PentaEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PentaEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PentaP1ElementResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PentaP1ElementResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PentaP1ElementResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PentaP1InputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PentaP1InputEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PentaP1InputEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/PetscOptionsAnalysesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PetscOptionsAnalysesEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PetscOptionsAnalysesEnum()
-%PETSCOPTIONSANALYSESENUM - Enum of PetscOptionsAnalyses
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=PetscOptionsAnalysesEnum()
-
-macro=StringToEnum('PetscOptionsAnalyses');
Index: sm/trunk/src/m/enum/PetscOptionsStringsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PetscOptionsStringsEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PetscOptionsStringsEnum()
-%PETSCOPTIONSSTRINGSENUM - Enum of PetscOptionsStrings
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=PetscOptionsStringsEnum()
-
-macro=StringToEnum('PetscOptionsStrings');
Index: sm/trunk/src/m/enum/PetscVecExternalResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PetscVecExternalResultEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PetscVecExternalResultEnum()
-%PETSCVECEXTERNALRESULTENUM - Enum of PetscVecExternalResult
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=PetscVecExternalResultEnum()
-
-macro=StringToEnum('PetscVecExternalResult');
Index: /issm/trunk/src/m/enum/PressureEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PressureEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PressureEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PressurePicardEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PressurePicardEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PressurePicardEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ProfilerEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ProfilerEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ProfilerEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ProfilingCurrentFlopsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ProfilingCurrentFlopsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ProfilingCurrentFlopsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ProfilingCurrentMemEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ProfilingCurrentMemEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ProfilingCurrentMemEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ProfilingSolutionTimeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ProfilingSolutionTimeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ProfilingSolutionTimeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PrognosticAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PrognosticAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PrognosticHydrostaticAdjustmentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticHydrostaticAdjustmentEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PrognosticHydrostaticAdjustmentEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PrognosticMinThicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticMinThicknessEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PrognosticMinThicknessEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PrognosticNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticNumRequestedOutputsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PrognosticNumRequestedOutputsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PrognosticPenaltyFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticPenaltyFactorEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PrognosticPenaltyFactorEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PrognosticRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticRequestedOutputsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PrognosticRequestedOutputsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PrognosticSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticSolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PrognosticSolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PrognosticSpcthicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticSpcthicknessEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PrognosticSpcthicknessEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PrognosticStabilizationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticStabilizationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PrognosticStabilizationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/PrognosticVertexPairingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticVertexPairingEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/PrognosticVertexPairingEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuBedEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuBedEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuBedEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuErrNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuErrNameEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuErrNameEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuInNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuInNameEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuInNameEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuIsdakotaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuIsdakotaEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuIsdakotaEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuMassFluxSegmentsPresentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMassFluxSegmentsPresentEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuMassFluxSegmentsPresentEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuMeltingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMeltingEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuMeltingEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuNumberofpartitionsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuNumberofpartitionsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuNumberofpartitionsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuNumberofresponsesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuNumberofresponsesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuNumberofresponsesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuOutNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuOutNameEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuOutNameEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuPartitionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuPartitionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuPartitionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuPressureEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuPressureEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuPressureEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuResponsedescriptorsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuResponsedescriptorsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuResponsedescriptorsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuSurfaceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuSurfaceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuSurfaceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuTemperatureEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuTemperatureEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuTemperatureEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuThicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuThicknessEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuThicknessEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuVariabledescriptorsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVariabledescriptorsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuVariabledescriptorsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuVxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuVxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuVyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuVyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/QmuVzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVzEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/QmuVzEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/RegularEnum.m
===================================================================
--- /issm/trunk/src/m/enum/RegularEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/RegularEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/RelativeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/RelativeEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=RelativeEnum()
-%RELATIVEENUM - Enum of Relative
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=RelativeEnum()
-
-macro=StringToEnum('Relative');
Index: /issm/trunk/src/m/enum/ResetPenaltiesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ResetPenaltiesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ResetPenaltiesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ResultsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ResultsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ResultsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/RheologyBbarAbsGradientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/RheologyBbarAbsGradientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/RheologyBbarAbsGradientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/RiftfrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/RiftfrontEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/RiftfrontEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/RiftfrontTypeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/RiftfrontTypeEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/RiftfrontTypeEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('RiftfrontType');
Index: /issm/trunk/src/m/enum/RiftsNumriftsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/RiftsNumriftsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/RiftsNumriftsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/RiftsRiftstructEnum.m
===================================================================
--- /issm/trunk/src/m/enum/RiftsRiftstructEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/RiftsRiftstructEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SaveResultsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SaveResultsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SaveResultsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ScaledEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ScaledEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ScaledEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SedimentHeadEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SedimentHeadEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/SedimentHeadEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('SedimentHead');
Index: /issm/trunk/src/m/enum/SedimentHeadOldEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SedimentHeadOldEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/SedimentHeadOldEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('SedimentHeadOld');
Index: /issm/trunk/src/m/enum/SedimentHeadResidualEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SedimentHeadResidualEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/SedimentHeadResidualEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('SedimentHeadResidual');
Index: /issm/trunk/src/m/enum/SegmentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SegmentEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SegmentEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SegmentOnIceShelfEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SegmentOnIceShelfEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SegmentOnIceShelfEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SegmentRiftfrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SegmentRiftfrontEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SegmentRiftfrontEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SeparateEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SeparateEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SeparateEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SeqEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SeqEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/SeqEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('Seq');
Index: /issm/trunk/src/m/enum/SettingsIoGatherEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SettingsIoGatherEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SettingsIoGatherEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SettingsLowmemEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SettingsLowmemEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SettingsLowmemEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SettingsOutputFrequencyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SettingsOutputFrequencyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SettingsOutputFrequencyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SettingsResultsAsPatchesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SettingsResultsAsPatchesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SettingsResultsAsPatchesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SettingsWaitonlockEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SettingsWaitonlockEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SettingsWaitonlockEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SoftMigrationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SoftMigrationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SoftMigrationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SolutionTypeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SolutionTypeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SolutionTypeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SpcDynamicEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SpcDynamicEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SpcDynamicEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SpcStaticEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SpcStaticEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SpcStaticEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SpcTransientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SpcTransientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SpcTransientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SsetEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SsetEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SteadystateMaxiterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SteadystateMaxiterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SteadystateMaxiterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SteadystateNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SteadystateNumRequestedOutputsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SteadystateNumRequestedOutputsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SteadystateReltolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SteadystateReltolEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SteadystateReltolEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SteadystateRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SteadystateRequestedOutputsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SteadystateRequestedOutputsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SteadystateSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SteadystateSolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SteadystateSolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StepEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StepEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StepEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StepResponsesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StepResponsesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StepResponsesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StokesApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StokesApproximationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StokesApproximationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StokesIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StokesIceFrontEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StokesIceFrontEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StokesSolverEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StokesSolverEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StokesSolverEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StressTensorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressTensorEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StressTensorEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StressTensorxxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressTensorxxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StressTensorxxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StressTensorxyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressTensorxyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StressTensorxyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StressTensorxzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressTensorxzEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StressTensorxzEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StressTensoryyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressTensoryyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StressTensoryyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StressTensoryzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressTensoryzEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StressTensoryzEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StressTensorzzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressTensorzzEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StressTensorzzEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StringArrayParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StringArrayParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StringArrayParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StringExternalResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StringExternalResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StringExternalResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/StringParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StringParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/StringParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SubelementMigration2Enum.m
===================================================================
--- /issm/trunk/src/m/enum/SubelementMigration2Enum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/SubelementMigration2Enum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('SubelementMigration2');
Index: /issm/trunk/src/m/enum/SubelementMigrationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SubelementMigrationEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/SubelementMigrationEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('SubelementMigration');
Index: /issm/trunk/src/m/enum/SurfaceAbsVelMisfitEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceAbsVelMisfitEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceAbsVelMisfitEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceAreaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceAreaEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceAreaEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceAverageVelMisfitEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceAverageVelMisfitEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceAverageVelMisfitEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceLogVelMisfitEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceLogVelMisfitEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceLogVelMisfitEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceLogVxVyMisfitEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceLogVxVyMisfitEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceLogVxVyMisfitEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceRelVelMisfitEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceRelVelMisfitEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceRelVelMisfitEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceSlopeAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceSlopeAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceSlopeAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceSlopeSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceSlopeSolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceSlopeSolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceSlopeXAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceSlopeXAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceSlopeXAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceSlopeXEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceSlopeXEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceSlopeXEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceSlopeYAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceSlopeYAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceSlopeYAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceSlopeYEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceSlopeYEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceSlopeYEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsBNegEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsBNegEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsBNegEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsBPosEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsBPosEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsBPosEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsDelta18oEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsDelta18oEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsDelta18oEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsDesfacEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsDesfacEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/SurfaceforcingsDesfacEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('SurfaceforcingsDesfac');
Index: /issm/trunk/src/m/enum/SurfaceforcingsHrefEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsHrefEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsHrefEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsIsdelta18oEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsIsdelta18oEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsIsdelta18oEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsIspddEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsIspddEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsIspddEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsIssmbgradientsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsIssmbgradientsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsIssmbgradientsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsMassBalanceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsMassBalanceEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsMassBalanceEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsMonthlytemperaturesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsMonthlytemperaturesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsMonthlytemperaturesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsS0pEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsS0pEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/SurfaceforcingsS0pEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('SurfaceforcingsS0p');
Index: /issm/trunk/src/m/enum/SurfaceforcingsSmbrefEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsSmbrefEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsSmbrefEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/TemperatureBasalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TemperatureBasalEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=TemperatureBasalEnum()
-%TEMPERATUREBASALENUM - Enum of TemperatureBasal
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=TemperatureBasalEnum()
-
-macro=StringToEnum('TemperatureBasal');
Index: /issm/trunk/src/m/enum/TemperatureEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TemperatureEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TemperatureEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TemperatureOldEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TemperatureOldEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TemperatureOldEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TemperaturePicardEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TemperaturePicardEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TemperaturePicardEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/TemperatureSurfaceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TemperatureSurfaceEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=TemperatureSurfaceEnum()
-%TEMPERATURESURFACEENUM - Enum of TemperatureSurface
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=TemperatureSurfaceEnum()
-
-macro=StringToEnum('TemperatureSurface');
Index: /issm/trunk/src/m/enum/ThermalAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalAnalysisEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThermalAnalysisEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThermalIsenthalpyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalIsenthalpyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThermalIsenthalpyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThermalMaxiterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalMaxiterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThermalMaxiterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThermalPenaltyFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalPenaltyFactorEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThermalPenaltyFactorEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThermalPenaltyLockEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalPenaltyLockEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThermalPenaltyLockEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThermalPenaltyThresholdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalPenaltyThresholdEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThermalPenaltyThresholdEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThermalSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalSolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThermalSolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThermalSpctemperatureEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalSpctemperatureEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThermalSpctemperatureEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThermalStabilizationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalStabilizationEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThermalStabilizationEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThicknessAbsGradientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThicknessAbsGradientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThicknessAbsGradientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThicknessAbsMisfitEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThicknessAbsMisfitEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThicknessAbsMisfitEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThicknessAcrossGradientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThicknessAcrossGradientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThicknessAcrossGradientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThicknessAlongGradientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThicknessAlongGradientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThicknessAlongGradientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ThicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThicknessEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ThicknessEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TimeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TimeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TimeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TimesteppingCflCoefficientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TimesteppingCflCoefficientEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TimesteppingCflCoefficientEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TimesteppingFinalTimeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TimesteppingFinalTimeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TimesteppingFinalTimeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TimesteppingStartTimeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TimesteppingStartTimeEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TimesteppingStartTimeEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TimesteppingTimeAdaptEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TimesteppingTimeAdaptEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TimesteppingTimeAdaptEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TimesteppingTimeStepEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TimesteppingTimeStepEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TimesteppingTimeStepEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ToolkitsOptionsAnalysesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ToolkitsOptionsAnalysesEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/ToolkitsOptionsAnalysesEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('ToolkitsOptionsAnalyses');
Index: /issm/trunk/src/m/enum/ToolkitsOptionsStringsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ToolkitsOptionsStringsEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/ToolkitsOptionsStringsEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('ToolkitsOptionsStrings');
Index: /issm/trunk/src/m/enum/TotalSmbEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TotalSmbEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TotalSmbEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TransientInputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientInputEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TransientInputEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TransientIsdiagnosticEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIsdiagnosticEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TransientIsdiagnosticEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TransientIsgiaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIsgiaEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/TransientIsgiaEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('TransientIsgia');
Index: /issm/trunk/src/m/enum/TransientIsgroundinglineEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIsgroundinglineEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TransientIsgroundinglineEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TransientIsprognosticEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIsprognosticEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TransientIsprognosticEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TransientIsthermalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIsthermalEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TransientIsthermalEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TransientNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientNumRequestedOutputsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TransientNumRequestedOutputsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TransientParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TransientParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TransientRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientRequestedOutputsEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TransientRequestedOutputsEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TransientSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientSolutionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TransientSolutionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TriaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TriaEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TriaEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/TriaInputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TriaInputEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/TriaInputEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('TriaInput');
Index: /issm/trunk/src/m/enum/TriaP1ElementResultEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TriaP1ElementResultEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TriaP1ElementResultEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/TriaP1InputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TriaP1InputEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=TriaP1InputEnum()
-%TRIAP1INPUTENUM - Enum of TriaP1Input
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=TriaP1InputEnum()
-
-macro=StringToEnum('TriaP1Input');
Index: /issm/trunk/src/m/enum/TriangleInterpEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TriangleInterpEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/TriangleInterpEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/TypeEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TypeEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=TypeEnum()
-%TYPEENUM - Enum of Type
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=TypeEnum()
-
-macro=StringToEnum('Type');
Index: /issm/trunk/src/m/enum/VectorParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VectorParamEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VectorParamEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VelEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VelEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VelEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VelocityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VelocityEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VelocityEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VerboseEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VerboseEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VerboseEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VertexEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VertexEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VertexEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VertexPIdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VertexPIdEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/VertexPIdEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('VertexPId');
Index: /issm/trunk/src/m/enum/VertexSIdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VertexSIdEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/VertexSIdEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('VertexSId');
Index: /issm/trunk/src/m/enum/VerticesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VerticesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VerticesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/ViscousHeatingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ViscousHeatingEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/ViscousHeatingEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VxAverageEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VxAverageEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VxAverageEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VxEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VxEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VxMeshEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VxMeshEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VxMeshEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VxPicardEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VxPicardEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VxPicardEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VyAverageEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VyAverageEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VyAverageEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VyEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VyEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VyMeshEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VyMeshEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VyMeshEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VyPicardEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VyPicardEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VyPicardEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VzEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VzMacAyealEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzMacAyealEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VzMacAyealEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VzMeshEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzMeshEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VzMeshEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VzPattynEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzPattynEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VzPattynEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VzPicardEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzPicardEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VzPicardEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/VzStokesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzStokesEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/VzStokesEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/WaterColumnOldEnum.m
===================================================================
--- /issm/trunk/src/m/enum/WaterColumnOldEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/WaterColumnOldEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/WaterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/WaterEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/WaterEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/WaterTransferEnum.m
===================================================================
--- /issm/trunk/src/m/enum/WaterTransferEnum.m	(revision 15396)
+++ /issm/trunk/src/m/enum/WaterTransferEnum.m	(revision 15396)
@@ -0,0 +1,11 @@
+function macro=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()
+
+macro=StringToEnum('WaterTransfer');
Index: /issm/trunk/src/m/enum/WatercolumnEnum.m
===================================================================
--- /issm/trunk/src/m/enum/WatercolumnEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/WatercolumnEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/WaterfractionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/WaterfractionEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/WaterfractionEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: sm/trunk/src/m/enum/WeakBalancethicknessAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/WeakBalancethicknessAnalysisEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=WeakBalancethicknessAnalysisEnum()
-%WEAKBALANCETHICKNESSANALYSISENUM - Enum of WeakBalancethicknessAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=WeakBalancethicknessAnalysisEnum()
-
-macro=StringToEnum('WeakBalancethicknessAnalysis');
Index: sm/trunk/src/m/enum/WeakBalancethicknessSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/WeakBalancethicknessSolutionEnum.m	(revision 15395)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=WeakBalancethicknessSolutionEnum()
-%WEAKBALANCETHICKNESSSOLUTIONENUM - Enum of WeakBalancethicknessSolution
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
-%
-%   Usage:
-%      macro=WeakBalancethicknessSolutionEnum()
-
-macro=StringToEnum('WeakBalancethicknessSolution');
Index: /issm/trunk/src/m/enum/XYEnum.m
===================================================================
--- /issm/trunk/src/m/enum/XYEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/XYEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/enum/XYZPEnum.m
===================================================================
--- /issm/trunk/src/m/enum/XYZPEnum.m	(revision 15395)
+++ /issm/trunk/src/m/enum/XYZPEnum.m	(revision 15396)
@@ -3,6 +3,6 @@
 %
 %   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
-%            Please read src/c/EnumDefinitions/README for more information
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
 %
 %   Usage:
Index: /issm/trunk/src/m/exp/expcreateprofile.m
===================================================================
--- /issm/trunk/src/m/exp/expcreateprofile.m	(revision 15395)
+++ /issm/trunk/src/m/exp/expcreateprofile.m	(revision 15396)
@@ -12,5 +12,5 @@
 
 %Get root of filename
-[path root ext ver]=fileparts(filename);
+[path root ext]=fileparts(filename);
 
 %Get profile
Index: /issm/trunk/src/m/exp/expflip.m
===================================================================
--- /issm/trunk/src/m/exp/expflip.m	(revision 15395)
+++ /issm/trunk/src/m/exp/expflip.m	(revision 15396)
@@ -6,5 +6,5 @@
 %
 
-a=expread(domainname,1);
+a=expread(domainname);
 
 for i=1:length(a),
Index: /issm/trunk/src/m/exp/exptool.m
===================================================================
--- /issm/trunk/src/m/exp/exptool.m	(revision 15395)
+++ /issm/trunk/src/m/exp/exptool.m	(revision 15396)
@@ -1,4 +1,4 @@
 function exptool(newfile,varargin)
-%EXPMASTER - allow to create, modify, add, cut, .. segments of domain outline together
+%EXPTOOL - allow to create, modify, add, cut, .. segments of domain outline together
 %
 %   this routine is used to create, modify, cut,... an Argus file (.exp)
Index: /issm/trunk/src/m/exp/flowlines.m
===================================================================
--- /issm/trunk/src/m/exp/flowlines.m	(revision 15395)
+++ /issm/trunk/src/m/exp/flowlines.m	(revision 15396)
@@ -38,6 +38,6 @@
 
 %check seed points
-%tria=TriaSearch(index,x,y,x0,y0);
-tria=tsearch(x,y,index,x0,y0);
+tria=TriaSearch(index,x,y,x0,y0);
+%tria=tsearch(x,y,index,x0,y0);
 pos=find(isnan(tria));
 x0(pos)=[];
@@ -70,6 +70,6 @@
 	%find current triangle
 	queue=find(~done);
-	%tria=TriaSearch(index,x,y,X(queue),Y(queue));
-	tria=tsearch(x,y,index,X(queue),Y(queue));
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+	%tria=tsearch(x,y,index,X(queue),Y(queue));
 
 	%check that the point is actually inside a triangle of the mesh
@@ -112,4 +112,5 @@
 
 %same process but reverse (vel=-vel) to have a vcomplete flow line
+queue=[];
 counter=1;
 X=x0; Y=y0;
@@ -120,6 +121,6 @@
 	%find current triangle
 	queue=find(~done);
-	%tria=TriaSearch(index,x,y,X(queue),Y(queue));
-	tria=tsearch(x,y,index,X(queue),Y(queue));
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+	%tria=tsearch(x,y,index,X(queue),Y(queue));
 
 	%check that the point is actually inside a triangle of the mesh
Index: /issm/trunk/src/m/exp/masktoexp.m
===================================================================
--- /issm/trunk/src/m/exp/masktoexp.m	(revision 15396)
+++ /issm/trunk/src/m/exp/masktoexp.m	(revision 15396)
@@ -0,0 +1,32 @@
+function masktoexp(x,y,mask,threshold,filename)
+%MASKTOEXP - mask to exp file
+%
+%   Usage:
+%      masktoexp(x,y,mask,threshold,filename)
+%
+%   Example:
+%      if A is a matrix of 0 and 1, and we want an exp for
+%      the transition:
+%      masktoexp(x,y,A,0.5,'contour.exp');
+%      To be combined with ExpSimplify
+
+%Create contour for threshold
+c=contourc(double(x),double(y),double(mask),[threshold threshold]);
+done=0; i=1; j=1;
+while (i<length(c))
+	num=c(2,i); i=i+1;
+	s(j).x=c(1,i:(i+num-1));
+	s(j).y=c(2,i:(i+num-1));
+	s(j).v=c(1,i);
+	i=i+num; j=j+1;
+end;
+
+%Create exp structure
+A=struct();
+for i=1:j-1,
+	A(i).x=s(i).x;
+	A(i).y=s(i).y;
+end;
+
+%write exp
+expwrite(A,filename);
Index: /issm/trunk/src/m/geometry/slope.m
===================================================================
--- /issm/trunk/src/m/geometry/slope.m	(revision 15395)
+++ /issm/trunk/src/m/geometry/slope.m	(revision 15396)
@@ -1,7 +1,8 @@
-function [sx,sy,s]=slope(md)
+function [sx,sy,s]=slope(md,surf)
 %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 variab;es are loaded from md once for all) 
@@ -18,10 +19,13 @@
 end
 
+if nargin==1,
+	surf=md.geometry.surface;
+end
 %compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
 [alpha beta]=GetNodalFunctionsCoeff(index,x,y);
 
 summation=[1;1;1];
-sx=(md.geometry.surface(index).*alpha)*summation;
-sy=(md.geometry.surface(index).*beta)*summation;
+sx=(surf(index).*alpha)*summation;
+sy=(surf(index).*beta)*summation;
 s=sqrt(sx.^2+sy.^2);
 
Index: /issm/trunk/src/m/io/structtonc.m
===================================================================
--- /issm/trunk/src/m/io/structtonc.m	(revision 15396)
+++ /issm/trunk/src/m/io/structtonc.m	(revision 15396)
@@ -0,0 +1,131 @@
+function [var_id,counter] = structtonc(ncid,fieldname,field,depth,var_id,counter,step);
+%STRUCTTONC- fill nc file with structure fields
+%
+%   WARNING: Do not use this function, this function is called
+%            by netcdf(model);
+%
+
+%update counter
+counter   = counter+1;
+
+%Check that field is not empty
+if isempty(field) | (isa(field,'struct') & numel(fields(field))==0),
+	if(step==1), disp(['skipping ' fieldname ' (empty)...']); end
+	return;
+end
+
+%Write field class
+[var_id,counter] = declareclass(ncid,[fieldname '_class'],class(field),depth,var_id,counter,step);
+
+%Double scalar
+if isa(field,'double') & numel(field)==1,
+	if step==1,
+		var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_DOUBLE',[]);
+	else
+		netcdf.putVar(ncid,var_id(counter),field);
+	end
+
+%Double vector
+elseif isa(field,'double') & size(field,2)==1,
+	if step==1,
+		dim_id          = netcdf.defDim(ncid,[fieldname '_size1'],size(field,1));
+		var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_DOUBLE',dim_id);
+	else
+		netcdf.putVar(ncid,var_id(counter),field);
+	end
+
+%double matrix
+elseif isa(field,'double') & size(field,2)>1,
+	if step==1,
+		dim1_id         = netcdf.defDim(ncid,[fieldname '_size1'],size(field,1));
+		dim2_id         = netcdf.defDim(ncid,[fieldname '_size2'],size(field,2));
+		var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_DOUBLE',[dim2_id dim1_id]);
+	else
+		netcdf.putVar(ncid,var_id(counter),transpose(field));
+	end
+
+%string
+elseif isa(field,'char') 
+		if step==1,
+			dim_id          = netcdf.defDim(ncid,[fieldname '_size1'],numel(field));
+			var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_CHAR',dim_id);
+		else
+			netcdf.putVar(ncid,var_id(counter),field);
+		end
+
+%Boolean of size 1
+elseif isa(field,'logical') & numel(field)==1,
+	if step==1,
+		var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_BYTE',[]);
+	else
+		netcdf.putVar(ncid,var_id(counter),int8(field));
+	end
+
+%Structures
+elseif isa(field,'struct'),
+	sublength = numel(field);
+	subfields = fields(field);
+	allsubfields = '';
+	for i=1:length(subfields),
+		allsubfields=[allsubfields subfields{i}];
+		if i~=length(subfields), allsubfields=[allsubfields ' ']; end
+	end
+	%Write size
+	if step==1,
+		var_id(counter) = netcdf.defVar(ncid,[fieldname '_length'],'NC_INT',[]);
+	else
+		netcdf.putVar(ncid,var_id(counter),sublength);
+	end
+	counter=counter+1;
+	%Write fields
+	if step==1,
+
+		dim_id          = netcdf.defDim(ncid,[fieldname '_fields_length'],numel(allsubfields));
+		var_id(counter) = netcdf.defVar(ncid,[fieldname '_fields'],'NC_CHAR',dim_id);
+	else
+		netcdf.putVar(ncid,var_id(counter),allsubfields);
+	end
+	for n=1:sublength,
+		for i=1:length(subfields),
+			[var_id,counter] = structtonc(ncid,[fieldname '.' subfields{i} '(' num2str(n) ')'],field(n).(subfields{i}),depth+1,var_id,counter,step);
+		end
+	end
+
+%Cell
+elseif isa(field,'cell'),
+	sublength = numel(field);
+	%Write size
+	if step==1,
+		var_id(counter) = netcdf.defVar(ncid,[fieldname '_length'],'NC_INT',[]);
+	else
+		netcdf.putVar(ncid,var_id(counter),sublength);
+	end
+	for i=1:sublength,
+		[var_id,counter] = structtonc(ncid,[fieldname '{' num2str(i) '}'],field{i},depth+1,var_id,counter,step);
+	end
+
+%Objects
+elseif isobject(field),
+	subfields = fields(field);
+	for i=1:length(subfields),
+		[var_id,counter] = structtonc(ncid,[fieldname '.' subfields{i}],field.(subfields{i}),depth+1,var_id,counter,step);
+	end
+else
+	disp(['skipping ' fieldname ' (format not supported)...']);
+end
+
+function [var_id,counter] = declareclass(ncid,fieldname,field,depth,var_id,counter,step);
+
+if isa(field,'char') 
+	if step==1,
+		dim_id          = netcdf.defDim(ncid,[fieldname '_length'],numel(field));
+		var_id(counter) = netcdf.defVar(ncid,fieldname,'NC_CHAR',dim_id);
+	else
+		netcdf.putVar(ncid,var_id(counter),field);
+	end
+else
+	error('class name is not a string');
+end
+
+%update counter
+counter   = counter+1;
Index: /issm/trunk/src/m/mesh/ExportGmsh.m
===================================================================
--- /issm/trunk/src/m/mesh/ExportGmsh.m	(revision 15396)
+++ /issm/trunk/src/m/mesh/ExportGmsh.m	(revision 15396)
@@ -0,0 +1,52 @@
+function ExportGmsh(md,filename)
+%EXPORTGMSH - export mesh to gmsh format
+%
+%   Usage:
+%      ExportGmsh(md,filename)
+
+t1=clock;fprintf('%s',['writing gmsh mesh file']);
+fid=fopen(filename,'w');
+
+%initialiaion
+fprintf(fid,'$MeshFormat \n');
+fprintf(fid,'2.2 0 8 \n');
+fprintf(fid,'$EndMeshFormat \n');
+fprintf(fid,'$Nodes \n');
+fprintf(fid,'%i \n',md.mesh.numberofvertices);
+np=0;
+%printing point positions
+for ii=1:md.mesh.numberofvertices
+	np = np+1;
+	fprintf(fid,'%g %14.7e %14.7e 0.0 \n',np,md.mesh.x(np),md.mesh.y(np));
+end
+
+fprintf(fid,'$EndNodes \n');
+fprintf(fid,'$Elements \n');
+fprintf(fid,'%i \n',md.mesh.numberofelements+size(md.mesh.segments,1));
+np=0;
+
+%printing elements caracteristics for boundaries
+
+for ii=1:size(md.mesh.segments,1)
+	np = np+1;
+	if(md.mesh.x(md.mesh.segments(np,1))==max(md.mesh.x(:))&&md.mesh.x(md.mesh.segments(np,2))==max(md.mesh.x(:))),
+		bc_id=1;
+	elseif(md.mesh.y(md.mesh.segments(np,1))==max(md.mesh.y(:))&&md.mesh.y(md.mesh.segments(np,2))==max(md.mesh.y(:))),
+		bc_id=2;
+	elseif(md.mesh.x(md.mesh.segments(np,1))==min(md.mesh.x(:))&&md.mesh.x(md.mesh.segments(np,2))==min(md.mesh.x(:))),
+		bc_id=3;
+	elseif(md.mesh.y(md.mesh.segments(np,1))==min(md.mesh.y(:))&&md.mesh.y(md.mesh.segments(np,2))==min(md.mesh.y(:))),
+		bc_id=4;
+  end
+		fprintf(fid,'%g 1 2 %g 1 %g %g \n',np,bc_id,md.mesh.segments(np,1),md.mesh.segments(np,2));
+end
+%and for the body
+body_id=1;
+for ii=1:md.mesh.numberofelements
+  np = np+1;
+  fprintf(fid,'%g 2 2 %g 3 %g %g %g \n',np,body_id,md.mesh.elements(ii,1),md.mesh.elements(ii,2),md.mesh.elements(ii,3));
+end
+fprintf(fid,'$EndElements \n');
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
Index: /issm/trunk/src/m/mesh/ProfileProjectOntoMesh.m
===================================================================
--- /issm/trunk/src/m/mesh/ProfileProjectOntoMesh.m	(revision 15395)
+++ /issm/trunk/src/m/mesh/ProfileProjectOntoMesh.m	(revision 15396)
@@ -53,5 +53,5 @@
 % (profile may start and/or end externally and/or cross holes in the model)
 
-ind=find(node_in_element(:,9)>0);
+ind=find(node_in_element(:,end)>0);
 newx=newx(ind,:);
 newy=newy(ind,:);
Index: /issm/trunk/src/m/mesh/bamg.m
===================================================================
--- /issm/trunk/src/m/mesh/bamg.m	(revision 15395)
+++ /issm/trunk/src/m/mesh/bamg.m	(revision 15396)
@@ -19,5 +19,5 @@
 %                         to apply several fields, use one column per field
 %   - gradation :         maximum ratio between two adjacent edges
-%   - Hessiantype :       0 -> use double P2 projection (default)
+%   - Hessiantype :       0 -> use double L2 projection (default)
 %                         1 -> use Green formula
 %   - KeepVertices :      try to keep initial vertices when adaptation is done on an existing mesh (default 1)
Index: /issm/trunk/src/m/mesh/roundmesh.m
===================================================================
--- /issm/trunk/src/m/mesh/roundmesh.m	(revision 15395)
+++ /issm/trunk/src/m/mesh/roundmesh.m	(revision 15396)
@@ -46,3 +46,2 @@
 
 end
-
Index: /issm/trunk/src/m/miscellaneous/normcdf_issm.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/normcdf_issm.m	(revision 15395)
+++ /issm/trunk/src/m/miscellaneous/normcdf_issm.m	(revision 15396)
@@ -7,3 +7,2 @@
 
 end
-
Index: /issm/trunk/src/m/miscellaneous/normfit_issm.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/normfit_issm.m	(revision 15395)
+++ /issm/trunk/src/m/miscellaneous/normfit_issm.m	(revision 15396)
@@ -4,33 +4,58 @@
 function [muhat,sigmahat,muci,sigmaci]=normfit_issm(x,alpha)
 
-%  remove any NaN
+	if ~exist('alpha','var')
+		alpha=0.05;
+	end
 
-	x=x(~isnan(x(:)));
-	n=length(x);
+%  check for any NaN in any columns
+
+	if ~any(any((isnan(x))))
 
 %  explicitly calculate the moments
 
-	muhat   =mean(x);
-	sigmahat=std(x);
+		muhat   =mean(x);
+		sigmahat=std(x);
 
-	if (nargout>2)
-		if ~exist('alpha','var')
-			alpha=0.05;
+		if (nargout>2)
+			prob=1.-alpha/2.;
+
+			if (size(x,1) == 1)
+				% operate like matlab normfit, mean, std, etc.
+				n=length(x);
+			else
+				n=size(x,1);
+			end
+
+			muci    =zeros(2,length(muhat   ));
+			sigmaci =zeros(2,length(sigmahat));
+
+			try
+				muci(1,:)   =muhat-tinv(prob,n-1)*sigmahat/sqrt(n);
+				muci(2,:)   =muhat+tinv(prob,n-1)*sigmahat/sqrt(n);
+				sigmaci(1,:)=sigmahat*sqrt((n-1)/chi2inv(prob   ,n-1));
+				sigmaci(2,:)=sigmahat*sqrt((n-1)/chi2inv(1.-prob,n-1));
+			catch me
+				muci(1,:)   =muhat;
+				muci(2,:)   =muhat;
+				sigmaci(1,:)=sigmahat;
+				sigmaci(2,:)=sigmahat;
+			end
 		end
-		prob=1.-alpha/2.;
 
-		try
-			muci(1,1)   =muhat-tinv(prob,n-1)*sigmahat/sqrt(n);
-			muci(2,1)   =muhat+tinv(prob,n-1)*sigmahat/sqrt(n);
-			sigmaci(1,1)=sigmahat*sqrt((n-1)/chi2inv(prob   ,n-1));
-			sigmaci(2,1)=sigmahat*sqrt((n-1)/chi2inv(1.-prob,n-1));
-		catch me
-			muci(1,1)   =muhat;
-			muci(2,1)   =muhat;
-			sigmaci(1,1)=sigmahat;
-			sigmaci(2,1)=sigmahat;
+	else
+
+%  must loop over columns, since number of elements could be different
+
+		muhat   =zeros(1,size(x,2));
+		sigmahat=zeros(1,size(x,2));
+		muci    =zeros(2,size(x,2));
+		sigmaci =zeros(2,size(x,2));
+
+%  remove any NaN and recursively call column
+
+		for j=1:size(x,2)
+			[muhat(j),sigmahat(j),muci(:,j),sigmaci(:,j)]=normfit_issm(x(~isnan(x(:,j)),j),alpha);
 		end
 	end
 
 end
-
Index: /issm/trunk/src/m/miscellaneous/norminv_issm.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/norminv_issm.m	(revision 15395)
+++ /issm/trunk/src/m/miscellaneous/norminv_issm.m	(revision 15396)
@@ -7,3 +7,2 @@
 
 end
-
Index: /issm/trunk/src/m/miscellaneous/prctile_issm.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/prctile_issm.m	(revision 15395)
+++ /issm/trunk/src/m/miscellaneous/prctile_issm.m	(revision 15396)
@@ -36,5 +36,5 @@
 %  check for any NaN in any columns
 
-		if ~any(isnan(x))
+		if ~any(any((isnan(x))))
 			x=sort(x,1);
 			n=size(x,1);
@@ -85,3 +85,2 @@
 
 end
-
Index: /issm/trunk/src/m/morphological/aggregation.m
===================================================================
--- /issm/trunk/src/m/morphological/aggregation.m	(revision 15396)
+++ /issm/trunk/src/m/morphological/aggregation.m	(revision 15396)
@@ -0,0 +1,64 @@
+function [mask,varargout]=aggregation(mask,windowsize,threshhold,varargin)
+%AGGREGATION - aggregation of an image to a lower sized image
+% 
+%  mask is an image of arbitrary size, format binary, with values 1 for foreground, and 0 for background
+%  mask is first convoluted with a square matrix of size windowsize (where windowsize is an even number), 
+%       it is then filtered according to the threshhold value, and finally subsampled using 1/windowsize as 
+%       sample scaling. 
+%  x,y can be provided as optional arguments, as coordinates of the center points of the mask. aggregation will 
+%       then return subsampled x,y arguments in output.
+% 
+%  Usage:   mask2=aggregation(mask,7,7^2/2);
+%           [mask2,x2,y2]=aggregation(mask,7,7^2,x,y];
+%
+%  See also CLOSING, OPENING, DILATION, EROSION
+
+%check input arguments  %{{{
+%even windowsize
+if mod(windowsize,2)==0,
+	error('windowsize should be an even number');
+end
+
+%check on presence of varargin: 
+optional=0;
+if nargin>3,
+	if nargin~=5,
+		help aggregation;
+		error('wrong number of optional arguments specified');
+	else
+		optional=1;
+		x=varargin{1};
+		y=varargin{2};
+	end
+end
+
+%check on presence of varargout: 
+if optional,
+	if nargout~=3,
+		help aggregation;
+		error('wrong number of optional output arguments specified');
+	end
+end
+%}}}
+
+%convolve mask
+matrix=ones(windowsize,windowsize); 
+mask=filter2(matrix,mask,'same');
+
+%apply threshhold
+pos=find(mask>threshhold); 
+pos2=find(mask<=threshhold); 
+mask(pos)=1;
+mask(pos2)=0;
+
+%mask has been transformed into double format from the filter2  operation. Bring back to binary. 
+mask=logical(mask);
+
+%subsample: 
+s=size(mask);
+mask=mask(1:windowsize:s(1),1:windowsize:s(2));
+
+if optional,
+	varargout{1}=x(1:windowsize:s(2));
+	varargout{2}=y(1:windowsize:s(1));
+end
Index: /issm/trunk/src/m/morphological/closing.m
===================================================================
--- /issm/trunk/src/m/morphological/closing.m	(revision 15396)
+++ /issm/trunk/src/m/morphological/closing.m	(revision 15396)
@@ -0,0 +1,5 @@
+function mask=closing(mask,neighboorhood)
+%closing algorithm using neighboorhood pixel neighboors.
+
+mask=dilation(mask,neighboorhood);
+mask=erosion(mask,neighboorhood);
Index: /issm/trunk/src/m/morphological/dilation.m
===================================================================
--- /issm/trunk/src/m/morphological/dilation.m	(revision 15396)
+++ /issm/trunk/src/m/morphological/dilation.m	(revision 15396)
@@ -0,0 +1,25 @@
+function mask=dilation(mask,neighboorhood)
+%deletion algorithm using 4 pixel neighboors.
+
+%convolve: 
+
+matrix=ones(3,3); 
+
+%4 neighboorhood: 
+%corners
+if neighboorhood==4,
+	matrix(1,1)=0;
+	matrix(1,3)=0;
+	matrix(3,1)=0;
+	matrix(3,3)=0;
+end
+%center
+matrix(2,2)=0;
+
+%convolve mask: 
+convol=filter2(matrix,mask,'same');
+
+pos=find(mask==0);
+pos2=find(convol(pos)~=0);
+
+mask(pos(pos2))=1;
Index: /issm/trunk/src/m/morphological/erosion.m
===================================================================
--- /issm/trunk/src/m/morphological/erosion.m	(revision 15396)
+++ /issm/trunk/src/m/morphological/erosion.m	(revision 15396)
@@ -0,0 +1,26 @@
+function mask=erosion(mask,neighboorhood)
+%erosion algorithm using neighboorhood pixel neighboors.
+
+%convolve: 
+
+matrix=ones(3,3); 
+
+%4 neighboorhood: 
+%corners
+if neighboorhood==4,
+	matrix(1,1)=0;
+	matrix(1,3)=0;
+	matrix(3,1)=0;
+	matrix(3,3)=0;
+end
+
+%center
+matrix(2,2)=0;
+
+%convolve mask: 
+convol=filter2(matrix,mask,'same');
+
+pos=find(mask==1);
+pos2=find(convol(pos)<neighboorhood);
+
+mask(pos(pos2))=0;
Index: /issm/trunk/src/m/morphological/nunataks.m
===================================================================
--- /issm/trunk/src/m/morphological/nunataks.m	(revision 15396)
+++ /issm/trunk/src/m/morphological/nunataks.m	(revision 15396)
@@ -0,0 +1,20 @@
+function [mask]=nunataks(mask)
+%NUNATAKS - bias mask towards increased 0 coverage
+% 
+%  mask is an image of arbitrary size, format binary, with values 1 for foreground, and 0 for background
+% 
+%  Usage:   mask=nunataks(mask)
+%           [mask]=aggregation(mask);
+%
+%  See also CLOSING, OPENING, DILATION, EROSION, AGGREGATION
+
+rocks=~mask;
+
+%matrices for convolution: 
+matrix=[0 1 0; 1 0 1; 0 1 0];
+
+%do not exist, i.e. locations that stand pretty much alone. 
+mask=filter2(matrix1,mask,'same');
+pos=find(~crocks & rocks);
+
+mask(pos)=0;
Index: /issm/trunk/src/m/morphological/opening.m
===================================================================
--- /issm/trunk/src/m/morphological/opening.m	(revision 15396)
+++ /issm/trunk/src/m/morphological/opening.m	(revision 15396)
@@ -0,0 +1,5 @@
+function mask=opening(mask,neighboorhood)
+%opening algorithm using neighboorhood pixel neighboors.
+
+mask=erosion(mask,neighboorhood);
+mask=dilation(mask,neighboorhood);
Index: /issm/trunk/src/m/morphological/vectorialize.m
===================================================================
--- /issm/trunk/src/m/morphological/vectorialize.m	(revision 15396)
+++ /issm/trunk/src/m/morphological/vectorialize.m	(revision 15396)
@@ -0,0 +1,11 @@
+function contours=vectorialize(mask,connectivity);
+
+	vec=bwboundaries(mask,connectivity);
+
+	contours=struct([]);
+	for i=1:length(vec),
+		contours(end+1).x=vec{i}(:,2);
+		contours(end).y=vec{i}(:,1);
+		contours(end).density=1;
+	end
+	contours(1).name='';
Index: /issm/trunk/src/m/os/dakotaversion.m
===================================================================
--- /issm/trunk/src/m/os/dakotaversion.m	(revision 15395)
+++ /issm/trunk/src/m/os/dakotaversion.m	(revision 15396)
@@ -20,6 +20,6 @@
 	tline=fgets(fid);
 	if ~ischar(tline), break, end
-	if  strncmp(tline,'#define DAKOTA_VERSION',22),
-		DAKOTA_VERSION=strtrim(strrep(tline(24:end),'"',''));
+	if  strncmp(tline,'#define _DAKOTA_VERSION_',24),
+		DAKOTA_VERSION=strtrim(strrep(tline(26:end),'"',''));
 	end
 end
Index: /issm/trunk/src/m/os/dakotaversion.py
===================================================================
--- /issm/trunk/src/m/os/dakotaversion.py	(revision 15395)
+++ /issm/trunk/src/m/os/dakotaversion.py	(revision 15396)
@@ -25,6 +25,6 @@
 
 	for tline in fid:
-		if strncmp(tline,'#define DAKOTA_VERSION',22):
-			DAKOTA_VERSION=tline[23:].replace('"','').strip()
+		if strncmp(tline,'#define _DAKOTA_VERSION_',24):
+			DAKOTA_VERSION=tline[25:].replace('"','').strip()
 			break
 
Index: /issm/trunk/src/m/os/issmscpout.m
===================================================================
--- /issm/trunk/src/m/os/issmscpout.m	(revision 15395)
+++ /issm/trunk/src/m/os/issmscpout.m	(revision 15396)
@@ -1,6 +1,6 @@
-function issmscpout(host,path,login,port,packages)
+function issmscpout(host,path,login,port,packages,varargin)
 %ISSMSCPOUT send packages to a host, using scp on unix, and pscp on windows
 %
-%   usage: issmscpout(host,path,packages)
+%   usage: issmscpout(host,path,login,port,packages)
 %
 %
@@ -8,4 +8,11 @@
 %get hostname
 hostname=oshostname();
+
+%are we dis-allowing symbolic links? 
+if nargin==6,
+	no_symlinks=1;
+else
+	no_symlinks=0;
+end
 
 %if hostname and host are the same, do a simple copy
@@ -16,5 +23,9 @@
 		eval(['cd ' path])
 		system(['rm -rf ' packages{i} ]);
-		system(['ln -s ' here '/' packages{i} ' .']);
+		if no_symlinks,
+			system(['cp  ' here '/' packages{i} ' .']);
+		else
+			system(['ln -s ' here '/' packages{i} ' .']);
+		end
 		eval(['cd ' here]);
 	end
Index: /issm/trunk/src/m/os/oshostname.m
===================================================================
--- /issm/trunk/src/m/os/oshostname.m	(revision 15395)
+++ /issm/trunk/src/m/os/oshostname.m	(revision 15396)
@@ -7,5 +7,5 @@
 
 if ispc(),
-	[status,hostname]=system('hostname | sed ''s/-//g''');
+	[status,hostname]=system('hostname');
 	if status, 
 		error('oshostname error message: could not run hostname command on windows os');
Index: /issm/trunk/src/m/parameterization/contourenvelope.m
===================================================================
--- /issm/trunk/src/m/parameterization/contourenvelope.m	(revision 15395)
+++ /issm/trunk/src/m/parameterization/contourenvelope.m	(revision 15396)
@@ -138,3 +138,2 @@
 end
 segments=segments(1:count-1,:);
-
Index: /issm/trunk/src/m/plot/applyoptions.m
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.m	(revision 15395)
+++ /issm/trunk/src/m/plot/applyoptions.m	(revision 15396)
@@ -243,8 +243,14 @@
 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};
-	expdisp(filenamei,gcf,stylei,getfieldvalue(options,'linewidth',1),getfieldvalue(options,'unit',1));
+	if length(linewidth)==1,
+		linewidthi=linewidth;
+	else
+		linewidthi=linewidth{i};
+	end
+	expdisp(filenamei,gcf,stylei,linewidthi,getfieldvalue(options,'unit',1));
 end
 
@@ -350,10 +356,10 @@
 	%box off
 	if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
-		A=expread([ jplsvn() '/projects/Exp/GreenlandBoxFront.exp']);
+		A=expread([ jplsvn() '/projects/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/Exp/Antarctica.exp']);
+		A=expread([ jplsvn() '/projects/ModelData/Exp/Antarctica.exp']);
 	else
 		error('applyoptions error message: hemisphere not defined');
@@ -434,37 +440,55 @@
 	%get current plot position
 	cplotpos=get(gca,'pos');
-	%compute inset position
-	PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
-	%show pos
+
 	X1=getfieldvalue(options,'insetx',xlim);
 	Y1=getfieldvalue(options,'insety',ylim);
-	if strcmpi(getfieldvalue(options,'showinset','off'),'on')
-		line(X1([1 2 2 1 1]),Y1([1 1 2 2 1]),zeros(1,5),'Color','k','LineWidth',2);
-	end
-
-	%Get current figure
-	ax1=gca;
-
-	%plot inset
-	axes('pos',PosInset);
-	copyobj(get(ax1,'children'),gca);
-	patch('Faces',[1 2 3 4 1],'Vertices',[X1([1 2 2 1])' Y1([1 1 2 2])'],'FaceColor','None','EdgeColor','k','LineWidth',2);
-
-	%applay options
-	options=removefield(options,'text',0);
-	options=removefield(options,'title',0);
-	options=removefield(options,'xlabel',0);
-	options=removefield(options,'ylabel',0);
-	options=removefield(options,'inset',0);
-	options=removefield(options,'offsetaxispos',0);
-	options=removefield(options,'showregion',0);
-	options=changefieldvalue(options,'colorbar',0);
-	options=changefieldvalue(options,'latlon','off');
-	options=changefieldvalue(options,'axis','equal off');
-	options=changefieldvalue(options,'xlim',getfieldvalue(options,'insetx',xlim));
-	options=changefieldvalue(options,'ylim',getfieldvalue(options,'insety',ylim));
-	applyoptions(md,data,options);
-
-	%back to main gca
-	set(gcf,'CurrentAxes',maingca)
-end
+
+	for i=1:length(getfieldvalue(options,'insetx')),
+		if length(insetpos)==4,
+			insetposi=insetpos;
+		else
+			insetposi=insetpos{i};
+		end
+		PosInseti=[cplotpos(1)+insetposi(1)*cplotpos(3),cplotpos(2)+insetposi(2)*cplotpos(4), insetposi(3)*cplotpos(3), insetposi(4)*cplotpos(4)];
+		%show pos
+		if iscell(X1),
+			X1i=X1{i};
+		else
+			X1i=X1;
+		end
+		if iscell(Y1),
+			Y1i=Y1{i};
+		else
+			Y1i=Y1;
+		end
+		if strcmpi(getfieldvalue(options,'showinset','off'),'on')
+			line(X1i([1 2 2 1 1]),Y1i([1 1 2 2 1]),zeros(1,5),'Color','k','LineWidth',2);
+		end
+
+		%Get current figure
+		ax1=gca;
+
+		%plot inset
+		axes('pos',PosInseti);
+		copyobj(get(ax1,'children'),gca);
+		patch('Faces',[1 2 3 4 1],'Vertices',[X1i([1 2 2 1])' Y1i([1 1 2 2])'],'FaceColor','None','EdgeColor','k','LineWidth',2);
+
+		%apply options
+		options=removefield(options,'text',0);
+		options=removefield(options,'title',0);
+		options=removefield(options,'xlabel',0);
+		options=removefield(options,'ylabel',0);
+		options=removefield(options,'inset',0);
+		options=removefield(options,'offsetaxispos',0);
+		options=removefield(options,'showregion',0);
+		options=changefieldvalue(options,'colorbar',0);
+		options=changefieldvalue(options,'latlon','off');
+		options=changefieldvalue(options,'axis','equal off');
+		options=changefieldvalue(options,'xlim',X1i);
+		options=changefieldvalue(options,'ylim',Y1i);
+		applyoptions(md,data,options);
+
+		%back to main gca
+		set(gcf,'CurrentAxes',maingca)
+	end
+end
Index: /issm/trunk/src/m/plot/colormaps/color_scale.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/color_scale.m	(revision 15396)
+++ /issm/trunk/src/m/plot/colormaps/color_scale.m	(revision 15396)
@@ -0,0 +1,74 @@
+function map = color_scale(n, theta, r, dir)
+%COLOR_SCALE Colormap with luminance and hue ramps and constant chroma.
+%   MAP = COLOR_SCALE(N, THETA, R, DIR) computes a colormap that works well 
+%   on color displays and also works well when printed on a grayscale 
+%   printer.
+%   
+%   The color map is computed using a simple path through L*a*b* space that
+%   approximates a uniform ramp in the L* direction, and a semicircular
+%   path in the a*-b* plane.
+%
+%   N is the number of colormap colors.  THETA is the angle (in degrees) in
+%   the a*-b* plane of the first color.  THETA is measured clockwise from
+%   the a* axis.  R is the radius of the semicircular path in the a*-b*
+%   plane.  DIR is either 'cw', for a clockwise traversal, or 'ccw', for a
+%   counterclockwise traversal.
+%
+%   All of the arguments are optional.  The default values are N = 256,
+%   THETA = 0, R = 50, and DIR = 'cw'.
+%
+%   COLOR_SCALE requires the Image Processing Toolbox version 4 or later.
+%
+%   Example
+%   -------
+%   Display a Radon transform image with colormaps produced by color_scale.
+%
+%       I = zeros(100,100);
+%       I(25:75, 25:75) = 1;
+%       theta = 0:180;
+%       [R,xp] = radon(I,theta);
+%       imshow(R,[],'InitialMag','fit')
+%       colormap(color_scale)
+%
+%       % Try it with different parameters.
+%       colormap(color_scale(256,0,88,'ccw'))
+%
+%   See also COLOR_SCALE_TOOL.
+
+%   Steve Eddins
+%   $Revision$  $Date$
+
+if nargin < 4
+    dir = 'cw';
+end
+
+if nargin < 3
+    r = 50;
+end
+
+if nargin < 2
+    theta = 0;
+end
+
+if nargin < 1
+    n = 256;
+end
+
+if strcmp(dir, 'cw')
+    angle_offset = -pi/2;
+else
+    angle_offset = pi/2;
+end
+
+theta = pi * theta / 180;
+theta_vec = linspace(theta, theta + angle_offset, n).';
+
+a = r*cos(theta_vec);
+b = r*sin(theta_vec);
+L = linspace(0, 100, n).';
+
+Lab = [L, a, b];
+
+cform = makecform('lab2srgb');
+
+map = applycform(Lab, cform);
Index: /issm/trunk/src/m/plot/colormaps/demmap.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/demmap.m	(revision 15395)
+++ /issm/trunk/src/m/plot/colormaps/demmap.m	(revision 15396)
@@ -1,15 +1,27 @@
-function cmap = demmap(ncolors,minZ,maxZ);
+function cmap = demmap(ncolors,minZ,maxZ,varargin);
 %DEMMAP - concatenate sea and land color depending on zmin and zmax
 %
 %   Usage:
-%      cmap = demmap(n,zmin,zmax)
+%      cmap = demmap(n,zmin,zmax,varargin)
+%
+%   Example:
+%      cmap = demmap(50,-300,1200);
+%      cmap = demmap(50,-300,1200,'dem');
+%      cmap = demmap(50,-300,1200,'ibcao');
 
+%Input checks
 if nargin<3,
 	help landseacolor
-	error('3 arguments necessary');
+	error('3 or 4 arguments necessary');
+elseif nargin>4,
+	help landseacolor
+	error('3 or 4 arguments necessary');
 end
 
-if minZ == maxZ;
-	maxZ = minZ+1;
+if nargin==4,
+	colorscheme = varargin{1};
+	if ~ischar(colorscheme), error('color scheme should be a string'); end
+else
+	colorscheme = 'dem';
 end
 
@@ -60,3 +72,8 @@
 
 clim = [cmn cmx];
-cmap = [seacolor(nsea);landcolor(nland).^1.3];
+
+if strcmpi(colorscheme,'dem'),
+	cmap = [seacolor(nsea);landcolor(nland).^1.3];
+elseif strcmpi(colorscheme,'ibcao');
+	cmap = ibcao(nsea,nland);
+end
Index: /issm/trunk/src/m/plot/colormaps/getcolormap.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/getcolormap.m	(revision 15395)
+++ /issm/trunk/src/m/plot/colormaps/getcolormap.m	(revision 15396)
@@ -23,10 +23,19 @@
 	map = jet(256);
 	map = map(128:end,:);
+elseif strcmpi(map,'damage'),
+	v=ver;
+	if any(strcmp('Image Processing Toolbox',{v.Name})),
+		map = color_scale(256,0,70,'ccw');
+		map = flipud(map);
+		map(1:2,:)=[0.7476    1.0000    1.0000; 0.7476    1.0000    1.0000];
+	else
+		error('damage colormap requires Image Processing Toolbox, please try another colormap');
+	end
 elseif strcmpi(map,'redblue'),
-	map = hsv(256);
+	map = hsv(128);
 	map = rgb2hsv(map);
 	map(:,2)       = max(min( abs(map(:,1)-0.5)/0.5 ,1),0);
-	map(1:128,1)   = 0.7;
-	map(129:end,1) = 1;
+	map(1:64,1)   = 0.7;
+	map(65:end,1) = 1;
 	map = hsv2rgb(map);
 elseif strcmpi(map,'Rignot'),
Index: /issm/trunk/src/m/plot/colormaps/ibcao.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/ibcao.m	(revision 15396)
+++ /issm/trunk/src/m/plot/colormaps/ibcao.m	(revision 15396)
@@ -0,0 +1,68 @@
+function map = ibcap(nsea,nland)
+%IBCAO - IBCAO color map
+%
+%   Usage:
+%      map = ibcap(nsea,nland)
+%
+%Downloaded from http://soliton.vm.bytemark.co.uk/pub/cpt-city/ibcao
+
+Jsea = [ ...
+0.18039 0.29020 0.57255
+0.18039 0.29020 0.57255
+0.05882 0.44314 0.65490
+0.05882 0.44314 0.65490
+0.02745 0.49804 0.73725
+0.02745 0.49804 0.73725
+0.01176 0.54510 0.78824
+0.01176 0.54510 0.78824
+0.00784 0.63529 0.83922
+0.00784 0.63529 0.83922
+0.06667 0.71765 0.86667
+0.06667 0.71765 0.86667
+0.17647 0.75294 1.00000
+0.17647 0.75294 1.00000
+0.23529 0.76471 0.85882
+0.23529 0.76471 0.85882
+0.24314 0.76471 0.83922
+0.24314 0.76471 0.83922
+0.25882 0.76078 0.81176
+0.25882 0.76078 0.81176
+0.27451 0.76078 0.76078
+0.27451 0.76078 0.76078
+0.41961 0.78431 0.74902
+0.41961 0.78431 0.74902
+0.60000 0.83137 0.74902
+0.60000 0.83137 0.74902
+];
+
+Jland = [ ...
+0.85098 0.84314 0.30588
+0.85098 0.84314 0.30588
+0.93333 0.89020 0.41961
+0.93333 0.89020 0.41961
+0.93725 0.80784 0.35686
+0.93725 0.80784 0.35686
+0.89804 0.74510 0.31765
+0.89804 0.74510 0.31765
+0.85098 0.63922 0.21961
+0.85098 0.63922 0.21961
+0.75686 0.55294 0.22353
+0.75686 0.55294 0.22353
+0.71765 0.50980 0.22353
+0.71765 0.50980 0.22353
+0.68627 0.48235 0.21961
+0.68627 0.48235 0.21961
+0.65490 0.45882 0.21569
+0.65490 0.45882 0.21569
+0.58824 0.39608 0.20392
+0.58824 0.39608 0.20392
+1.00000 1.00000 1.00000
+];
+
+lsea = length(Jsea);
+ysea = interp1(1:lsea,Jsea,linspace(1,lsea,nsea),'*linear');
+
+lland = length(Jland);
+yland = interp1(1:lland,Jland,linspace(1,lland,nland),'*linear');
+
+map=[ysea;yland];
Index: /issm/trunk/src/m/plot/colormaps/seacolor.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/seacolor.m	(revision 15395)
+++ /issm/trunk/src/m/plot/colormaps/seacolor.m	(revision 15396)
@@ -56,3 +56,2 @@
 end
 y = interp1(1:l,J,linspace(1,l,n),'*linear');
-
Index: /issm/trunk/src/m/plot/curvedarrow.m
===================================================================
--- /issm/trunk/src/m/plot/curvedarrow.m	(revision 15395)
+++ /issm/trunk/src/m/plot/curvedarrow.m	(revision 15396)
@@ -24,5 +24,5 @@
 	%compute some values out of (x1,y1) and (x2,y2)
 	length=distance*angle;
-	
+
 	if exist(options,'widthratio'),
 		widthratio=getfieldvalue(options,'widthratio');
@@ -57,5 +57,5 @@
 		m=-m;
 	end
-	
+
 	if exist(options,'arrowlength'),
 		d=arrowlength;
@@ -63,5 +63,5 @@
 		d=abs((distance*angle)*ratio);
 	end
-	
+
 	%G is d distance from middle of E and F: 
 	G=(E+F)/2+d*m;
Index: /issm/trunk/src/m/plot/googlemaps.m
===================================================================
--- /issm/trunk/src/m/plot/googlemaps.m	(revision 15396)
+++ /issm/trunk/src/m/plot/googlemaps.m	(revision 15396)
@@ -0,0 +1,226 @@
+function md = googlemaps(md,ullat,ullon,lrlat,lrlon,varargin)
+%GOOGLEMAPS - Extract image from Google maps for given region
+%
+%   Usage:
+%       md = googlemaps(md)
+%       md = googlemaps(md,ullat,ullon,lrlat,lrlon)
+%       md = googlemaps(md,ullat,ullon,lrlat,lrlon,options)
+%
+%   - ullat,ullon: Upper Left corner latitude and longitude
+%   - lrlat,lrlon: Lower Right corner latitude and longitude
+%
+%   Available options:
+%      - zoom: zoom level, between 1 and 21 (default dynamically calculated)
+
+%Parse inputs
+if nargin<=5,
+	options=pairoptions;
+else
+	options=varargin{:};
+	if ~isa(options,'pairoptions'),
+		options=pairoptions(varargin{:});
+	end
+end
+if nargin==1,
+	%Get xlim and ylim (used to extract Google maps image)
+	xlim=getfieldvalue(options,'xlim',[min(md.mesh.x) max(md.mesh.x)]);
+	ylim=getfieldvalue(options,'ylim',[min(md.mesh.y) max(md.mesh.y)]);
+	if strcmpi(md.mesh.hemisphere,'n'),
+		[latlist lonlist]= xy2ll(...
+			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
+			[linspace(ylim(1),ylim(1),100) linspace(ylim(1),ylim(2),100) linspace(ylim(2),ylim(2),100) linspace(ylim(2),ylim(1),100)],...
+			+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		[latlist lonlist]= xy2ll(...
+			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
+			[linspace(ylim(1),ylim(1),100) linspace(ylim(1),ylim(2),100) linspace(ylim(2),ylim(2),100) linspace(ylim(2),ylim(1),100)],...
+			-1,0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+
+	%Image corners in lat/long
+	ullat = max(latlist); ullon = min(lonlist);
+	lrlat = min(latlist); lrlon = max(lonlist);
+elseif nargin>1 & nargin<5,
+	help googlemaps
+	error('Wrong usage');
+end
+
+%Get region specific projection parameters
+EPSGgoogle = 'EPSG:3785';   % Mercator       http://www.spatialreference.org/ref/epsg/3785/
+if strcmpi(md.mesh.hemisphere,'n'),
+	EPSGlocal = 'EPSG:3413'; % UPS Greenland  http://www.spatialreference.org/ref/epsg/3413/
+elseif strcmpi(md.mesh.hemisphere,'s'),
+	EPSGlocal = 'EPSG:3031'; % UPS Antarctica http://www.spatialreference.org/ref/epsg/3031/
+else
+	error('field hemisphere should either be ''n'' or ''s''');
+end
+
+%Find optimal zoom
+if exist(options,'zoom'),
+	zoom = getfieldvalue(options,'zoom');
+else
+	zoom = optimalzoom(ullat,ullon,lrlat,lrlon);
+	display(['googlemaps info: default zoom level ' num2str(zoom)]);
+end
+scale   = 1;
+maxsize = 640;
+bottom  = 50;
+
+%convert all these coordinates to pixels
+[ulx, uly]= latlontopixels(ullat, ullon, zoom);
+[lrx, lry]= latlontopixels(lrlat, lrlon, zoom);
+
+%calculate total pixel dimensions of final image
+dx = lrx - ulx;
+dy = uly - lry;
+
+%calculate rows and columns
+cols = ceil(dx/maxsize);
+rows = ceil(dy/(maxsize-bottom));
+
+%calculate pixel dimensions of each small image
+width   = ceil(dx/cols);
+height  = ceil(dy/rows);
+heightplus = height + bottom;
+
+%Initialize final image
+final = zeros(floor(dy),floor(dx),3);%RGB image
+for x=0:cols-1,
+	for y=0:rows-1,
+		dxn = width  * (0.5 + x);
+		dyn = height * (0.5 + y);
+		[latn, lonn] = pixelstolatlon(ulx + dxn, uly - dyn - bottom/2, zoom);
+		position = [num2str(latn) ',' num2str(lonn)];
+		disp(['Google Earth tile: ' num2str(x) '/' num2str(cols-1) ' ' num2str(y) '/' num2str(rows-1) ' (center: ' position ')']);
+		%Google maps API: http://developers.google.com/maps/documentation/staticmaps/
+		params = [...
+			'center=' position ...
+			'&zoom=' num2str(zoom)...
+			'&size=' num2str(width) 'x' num2str(heightplus)...
+			'&maptype=satellite'...
+			'&sensor=false'...
+			'&scale=' num2str(scale)];
+		url = ['http://maps.google.com/maps/api/staticmap?' params];
+		[X, map]=imread(url,'png');
+		X=ind2rgb(X,map);
+		indx1 = floor(x*width)+1;
+		indx2 = min(floor(dx),floor(x*width)+size(X,2));
+		indy1 = floor(y*height)+1;
+		indy2 = min(floor(dy),floor(y*height)+size(X,1));
+		final(indy1:indy2,indx1:indx2,:)=X(1:indy2-indy1+1,1:indx2-indx1+1,:);
+	end
+end
+
+%Write image
+imwrite(final,'temp.png','png')
+[ulmx ulmy]=ll2mercator(ullat,ullon);
+[lrmx lrmy]=ll2mercator(lrlat,lrlon);
+
+%Create Geotiff for Mercator projection 
+[status,result] = system(['gdal_translate -of Gtiff -co "tfw=yes"  -a_ullr '...
+	num2str(ulmx,'%15.8f') ' ' num2str(ulmy,'%15.8f') ' ' num2str(lrmx,'%15.8f') ' ' num2str(lrmy,'%15.8f')...
+	' -a_srs "' EPSGgoogle '" "temp.png" "temp.tiff"']);
+delete('temp.png');
+
+%If not gdal, exit
+if status~=0,
+	disp('googlemaps info: gdal not found or not working properly, the Google image will not be transformed');
+	[gX gY]=meshgrid(ulx:ulx+size(final,2)-1,uly:-1:uly-size(final,1)+1);
+	[LAT LON]=pixelstolatlon(gX,gY, zoom);
+	if strcmpi(md.mesh.hemisphere,'n'),
+		[X Y]=ll2xy(LAT,LON,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		[X Y]=ll2xy(LAT,LON,-1,0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+	md.radaroverlay.pwr=final;
+	md.radaroverlay.x=X;
+	md.radaroverlay.y=Y;
+	return
+end
+
+%reproject from mercator (EPSG:3785) to UPS Ant (EPSG:3031)
+[status,result] = system(['gdalwarp  -s_srs ' EPSGgoogle ' -t_srs ' EPSGlocal ' temp.tiff temp2.tiff']);
+delete('temp.tiff','temp.tfw');
+
+%If previous command failed, exit
+if ~isempty(strfind(result,'ERROR')),
+	disp(' ');disp('googlemaps info: gdal not working properly (missing proj.4 library?), Google image will not be transformed');
+	disp(result);
+	[gX gY]=meshgrid(ulx:ulx+size(final,2)-1,uly:-1:uly-size(final,1)+1);
+	[LAT LON]=pixelstolatlon(gX,gY, zoom);
+	if strcmpi(md.mesh.hemisphere,'n'),
+		[X Y]=ll2xy(LAT,LON,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		[X Y]=ll2xy(LAT,LON,-1,0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+	md.radaroverlay.pwr=final;
+	md.radaroverlay.x=X;
+	md.radaroverlay.y=Y;
+	return
+end
+
+%Put everything in model
+[status output]=system('gdalinfo temp2.tiff | grep "Upper Left"');
+ul = sscanf(output,'Upper Left  (%f, %f)');
+[status output]=system('gdalinfo temp2.tiff | grep "Lower Right"');
+lr = sscanf(output,'Lower Right (%f, %f)');
+[status output]=system('gdalinfo temp2.tiff | grep "Size is"');
+si = sscanf(output,'Size is %i, %i');
+x_m=linspace(ul(1),lr(1),si(1));
+y_m=linspace(ul(2),lr(2),si(2)); %We need to reverse y_m because the image is read upside down by matlab
+final=imread('temp2.tiff');
+delete('temp2.tiff');
+
+md.radaroverlay.pwr=final;
+md.radaroverlay.x=x_m;
+md.radaroverlay.y=y_m;
+
+end
+function [px py]=latlontopixels(lat, lon, zoom),
+	EARTH_RADIUS = 6378137;
+	EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS;
+	INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0;
+	ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0;
+
+	[mx,my]=ll2mercator(lat,lon);
+	res = INITIAL_RESOLUTION / (2^zoom);
+	px = (mx + ORIGIN_SHIFT) / res;
+	py = (my + ORIGIN_SHIFT) / res;
+end
+
+function [lat lon]=pixelstolatlon(px, py, zoom),
+	EARTH_RADIUS = 6378137;
+	EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS;
+	INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0;
+	ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0;
+
+	res = INITIAL_RESOLUTION / (2^zoom);
+	mx = px * res - ORIGIN_SHIFT;
+	my = py * res - ORIGIN_SHIFT;
+	[lat lon] = mercator2ll(mx,my);
+end
+function  zoom = optimalzoom(ullat,ullon,lrlat,lrlon)
+
+	EARTH_RADIUS = 6378137;
+	EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS;
+	INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0;
+
+	optimalsize = 1000; %Number of pixels in final image
+
+	[ulmx ulmy]=ll2mercator(ullat,ullon);
+	[lrmx lrmy]=ll2mercator(lrlat,lrlon);
+	distance = sqrt((lrmx-ulmx)^2 + (lrmy-ulmy)^2);
+
+	zoom1 = floor(log(INITIAL_RESOLUTION*optimalsize/(lrmx-ulmx))/log(2));
+	zoom2 = floor(log(INITIAL_RESOLUTION*optimalsize/(ulmy-lrmy))/log(2));
+
+	zoom=max(zoom1,zoom2);
+
+	zoom = min(max(1,zoom),21);
+end
Index: /issm/trunk/src/m/plot/manualcb.m
===================================================================
--- /issm/trunk/src/m/plot/manualcb.m	(revision 15396)
+++ /issm/trunk/src/m/plot/manualcb.m	(revision 15396)
@@ -0,0 +1,118 @@
+function manualcb(zmin,zmax,cmap,varargin)
+%MANUALCB - custom colorbar
+%
+%   Usage:
+%      manualcb(min,max,colormap,options)
+%
+%   Available options:
+%      - 'fontsize'    : default is 12
+%      - 'smallbars'   : bars next to each tick (default is false)
+%      - 'position'    : colorbar position in normalized units
+%      - 'orientation' : 'vertical' (default) or 'horizontal'
+%      - 'title'       : colorbar title
+%      - 'tick'        : specified values of tick labels
+%      - 'ticksep'     : spacing between ticks
+
+%check inputs
+if nargin<3,
+	help manualcb
+	error('bad usage');
+end
+if zmin>zmax,
+	error('zmin should be smaller than zmax');
+end
+
+%Get plot axes
+mainaxes = gca;
+
+%process options
+options = pairoptions(varargin{:});
+if exist(options,'tick') & exist(options,'ticksep'),
+	error('only one of tick or ticksep can be specified');
+end
+fontsize  = getfieldvalue(options,'fontsize',12);
+smallbars = getfieldvalue(options,'smallbars',false);
+
+%Colorbar position
+if ~exist(options,'position'),
+	position = plotboxpos;
+	xstart   = position(1)+position(3)+0.01;
+	ystart   = position(2);
+	width    = .02;
+	height   = position(4);
+else
+	position = getfieldvalue(options,'position');
+	xstart = position(1);
+	ystart = position(2);
+	width  = position(3);
+	height = position(4);
+end
+axes('Units','normalized','Position',[xstart ystart width height],'XTickLabel','','YTickLabel','','Visible','on');
+xlim([0 1]);
+ylim([0 1]);
+
+%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]');
+end
+ytick  = (ztick-zmin)/(zmax-zmin);
+
+%Display colorbar
+hold on
+if strcmpi(getfieldvalue(options,'orientation','vertical'),'vertical'),
+	image_rgb = ind2rgb(repmat(uint16(1:length(cmap))',1,2),cmap);
+else
+	image_rgb = ind2rgb(repmat(uint16(1:length(cmap))',1,2)',cmap);
+end
+imagesc([0 1],[0 1],image_rgb);
+patch([0,0,1,1],[0,1,1,0],'k','FaceColor','none','Clipping','off')
+
+%Add ticks
+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 smallbars,
+		for i=1:numel(ztick)
+			patch([0.8 1.0],[ytick(i) ytick(i)],'k')
+			patch([0.0 0.2],[ytick(i) ytick(i)],'k')
+		end
+	end
+else
+	%Use FOR LOOP otherwise numbers are not correcly centered
+	for i=1:length(ytick), text(ytick(i),-0.5,num2str(ztick(i)),'HorizontalAlignment','center','VerticalAlignment','top','FontSize',fontsize); end
+	if smallbars,
+		for i=1:numel(ztick)
+			patch([ytick(i) ytick(i)],[0.8 1.0],[ytick(i) ytick(i)],'k')
+			patch([ytick(i) ytick(i)],[0.0 0.2],[ytick(i) ytick(i)],'k')
+		end
+	end
+end
+
+if exist(options,'title'),
+	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);
+	end
+end
+if exist(options,'ylabel'),
+	ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize);
+end
+	
+%Back to original axes
+if strcmpi(getfieldvalue(options,'showregion',0),0)
+	axes(mainaxes);
+end
+
+function delta = dtick(range)
+%Tick intervals
+m = 10^floor(log10(range));
+p = ceil(range/m);
+if p <= 1,     delta = .1*m;
+elseif p == 2, delta = .2*m;
+elseif p <= 5, delta = .5*m;
+else           delta = m;
+end
Index: /issm/trunk/src/m/plot/plot_googlemaps.m
===================================================================
--- /issm/trunk/src/m/plot/plot_googlemaps.m	(revision 15396)
+++ /issm/trunk/src/m/plot/plot_googlemaps.m	(revision 15396)
@@ -0,0 +1,107 @@
+function plot_googlemaps(md,data,options,plotlines,plotcols,i)
+%PLOT_GOOGLEMAPS - superimpose Google maps to a given field
+%
+%   Usage:
+%      plot_googlemaps(md,data,options,plotlines,plotcols,i)
+%
+%   See also: PLOTMODEL
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,data,options);
+
+%check is2d
+if ~is2d, 
+	error('buildgridded error message: gridded not supported for 3d meshes, project on a layer');
+end
+
+if ~any(isnan(md.radaroverlay.x(:))) & ~any(isnan(md.radaroverlay.y(:))) & ~any(isnan(md.radaroverlay.pwr(:))) ...
+		& size(md.radaroverlay.pwr,3)==3 & size(md.radaroverlay.x,2)==size(md.radaroverlay.pwr,2),
+	disp('plot_googlemaps info: the RGB image held by the model is being used');
+else
+	disp('Extracting image from Google maps...');
+
+	%Get xlim and ylim (used to extract radar image)
+	xlim=getfieldvalue(options,'xlim',[min(x) max(x)]);
+	ylim=getfieldvalue(options,'ylim',[min(y) max(y)]);
+	if strcmpi(md.mesh.hemisphere,'n'),
+		[latlist lonlist]= xy2ll(...
+			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
+			[linspace(ylim(1),ylim(1),100) linspace(ylim(1),ylim(2),100) linspace(ylim(2),ylim(2),100) linspace(ylim(2),ylim(1),100)],...
+			+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		[latlist lonlist]= xy2ll(...
+			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
+			[linspace(ylim(1),ylim(1),100) linspace(ylim(1),ylim(2),100) linspace(ylim(2),ylim(2),100) linspace(ylim(2),ylim(1),100)],...
+			-1,0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+
+	%Image corners in lat/long
+	ullat = max(latlist); ullon = min(lonlist);
+	lrlat = min(latlist); lrlon = max(lonlist);
+
+	md=googlemaps(md,ullat,ullon,lrlat,lrlon,options);
+end
+
+%Process image from model
+final = double(md.radaroverlay.pwr)/double(max(md.radaroverlay.pwr(:))); %rescale between 0 and 1
+
+%Get some options
+transparency = getfieldvalue(options,'transparency',.3);
+
+%Prepare grid
+if size(md.radaroverlay.x,1)==1 | size(md.radaroverlay.x,2)==1,
+	xmin=min(md.radaroverlay.x);
+	ymax=max(md.radaroverlay.y);
+	xspacing=md.radaroverlay.x(2)-md.radaroverlay.x(1);
+	yspacing=md.radaroverlay.y(2)-md.radaroverlay.y(1);
+	nlines=length(md.radaroverlay.y);
+	ncols =length(md.radaroverlay.x);
+		[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x/getfieldvalue(options,'unit',1),y/getfieldvalue(options,'unit',1),...
+			data,xmin,ymax,xspacing,yspacing,nlines,ncols,NaN);
+else
+	X = md.radaroverlay.x;
+	Y = md.radaroverlay.y;
+	data_grid=InterpFromMeshToMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X(:),Y(:),'default',NaN); data_grid=reshape(data_grid,size(X));
+	x_m=X(1,:); y_m=Y(:,1);
+end
+data_nan=isnan(data_grid);
+if exist(options,'caxis'),
+	caxis_opt=getfieldvalue(options,'caxis');
+	data_grid(find(data_grid<caxis_opt(1)))=caxis_opt(1);
+	data_grid(find(data_grid>caxis_opt(2)))=caxis_opt(2);
+	data_min=caxis_opt(1);
+	data_max=caxis_opt(2);
+else
+	data_min=min(data_grid(:));
+	data_max=max(data_grid(:));
+end
+colorm = getcolormap(options);
+image_rgb = ind2rgb(uint16((data_grid - data_min)*(length(colorm)/(data_max-data_min))),colorm);
+
+alpha=ones(size(data_grid));
+alpha(find(~data_nan))=transparency;
+alpha=repmat(alpha,[1 1 3]);
+
+final=alpha.*final+(1-alpha).*image_rgb;
+
+%Select plot area 
+subplotmodel(plotlines,plotcols,i,options);
+
+h=imagesc(x_m,y_m,final);
+
+%last step: mesh gridded?
+if exist(options,'edgecolor'),
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch('Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',data_grid(1)*ones(size(x)),'FaceColor','none','EdgeColor',getfieldvalue(options,'edgecolor'));
+end
+
+%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 off'); % default axis
+applyoptions(md,data,options);
+end
Index: /issm/trunk/src/m/plot/plot_gridded.m
===================================================================
--- /issm/trunk/src/m/plot/plot_gridded.m	(revision 15395)
+++ /issm/trunk/src/m/plot/plot_gridded.m	(revision 15396)
@@ -53,5 +53,11 @@
 
 %shading interp;
-h=imagesc(xlim,ylim,data_grid);set(gca,'YDir','normal');
+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);
+end
+axis xy
 
 %last step: mesh gridded?
Index: /issm/trunk/src/m/plot/plot_manager.m
===================================================================
--- /issm/trunk/src/m/plot/plot_manager.m	(revision 15395)
+++ /issm/trunk/src/m/plot/plot_manager.m	(revision 15396)
@@ -157,4 +157,10 @@
 
 %Figure out if this is a semi-transparent plot.
+if exist(options,'googlemaps'),
+	plot_googlemaps(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a semi-transparent plot.
 if exist(options,'gridded'),
 	plot_gridded(md,data,options,nlines,ncols,i);
@@ -179,5 +185,10 @@
 
 %standard plot:
-subplot(nlines,ncols,i);
+if exist(options,'asymsubplot')
+	id=getfieldvalue(options,'asymsubplot',i);
+	subplot(nlines,ncols,id);
+else
+	subplot(nlines,ncols,i);
+end
 
 %plot unit
Index: /issm/trunk/src/m/plot/plot_streamlines.m
===================================================================
--- /issm/trunk/src/m/plot/plot_streamlines.m	(revision 15395)
+++ /issm/trunk/src/m/plot/plot_streamlines.m	(revision 15396)
@@ -18,4 +18,5 @@
 %initialize flowpath
 streamlines=getfieldvalue(options,'streamlines');
+edgecolor=getfieldvalue(options,'streamlines_color','y');
 if ischar(streamlines) & strcmpi(streamlines,'on');
 	streamlines=60;
@@ -38,4 +39,4 @@
 hold on
 for i=1:length(flowpath)
-	patch('Xdata',[flowpath(i).x;NaN],'Ydata',[flowpath(i).y;NaN],'facecolor','none','edgecolor','y');
+	patch('Xdata',[flowpath(i).x;NaN],'Ydata',[flowpath(i).y;NaN],'facecolor','none','edgecolor',edgecolor);
 end
Index: /issm/trunk/src/m/plot/plot_transient_movie.m
===================================================================
--- /issm/trunk/src/m/plot/plot_transient_movie.m	(revision 15395)
+++ /issm/trunk/src/m/plot/plot_transient_movie.m	(revision 15396)
@@ -65,5 +65,5 @@
 function apply_options_movie(md,options,titlestring)
 	%apply options
-	options=addfielddefault(options,'title',titlestring);
+	options=changefieldvalue(options,'title',titlestring);
 	options=addfielddefault(options,'colorbar',1);
 	applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plotboxpos.m
===================================================================
--- /issm/trunk/src/m/plot/plotboxpos.m	(revision 15395)
+++ /issm/trunk/src/m/plot/plotboxpos.m	(revision 15396)
Index: /issm/trunk/src/m/plot/plotdoc.m
===================================================================
--- /issm/trunk/src/m/plot/plotdoc.m	(revision 15395)
+++ /issm/trunk/src/m/plot/plotdoc.m	(revision 15396)
@@ -115,5 +115,5 @@
 disp('       ''expdisp'': plot exp file on top of a data plot. provide exp file as an argument (use a cell of strings if more than one)');
 disp('       ''expstyle'': marker style for expdisp plot (use a cell of strings if more than one)');
-disp('       ''linewidth'': line width for expdisp plot');
+disp('       ''linewidth'': line width for expdisp plot (use a cell of strings if more than one)');
 disp('       ''border'': size of display border (in pixels). active only for overlay plots');
 disp('       ''text'': print string, use a cell of strings if more than one');
Index: /issm/trunk/src/m/plot/plotmodel.m
===================================================================
--- /issm/trunk/src/m/plot/plotmodel.m	(revision 15395)
+++ /issm/trunk/src/m/plot/plotmodel.m	(revision 15396)
@@ -8,9 +8,13 @@
 subplotwidth=ceil(sqrt(options.numberofplots));
 
+%Get figure number and number of plots
+figurenumber=options.figurenumber;
+numberofplots=options.numberofplots;
+
 %if nlines and ncols specified, then bypass.
 if exist(options.list{1},'nlines'),
 	nlines=getfieldvalue(options.list{1},'nlines');
 else 
-	nlines=subplotwidth;
+	nlines=ceil(numberofplots/subplotwidth);
 end
 
@@ -25,8 +29,4 @@
 	error('plotmodel error message: nlines and ncols  need to be specified together, or not at all');
 end
-
-%Get figure number and number of plots
-figurenumber=options.figurenumber;
-numberofplots=options.numberofplots;
 
 %go through subplots
Index: /issm/trunk/src/m/plot/scaleruler.m
===================================================================
--- /issm/trunk/src/m/plot/scaleruler.m	(revision 15395)
+++ /issm/trunk/src/m/plot/scaleruler.m	(revision 15396)
@@ -6,6 +6,8 @@
 
 %get options
-structure=getfieldvalue(options,'scaleruler');
-fontsize=getfieldvalue(options,'scaleruler_fontsize',16);
+structure  = getfieldvalue(options,'scaleruler');
+fontcolor  = getfieldvalue(options,'fontcolor','k');
+fontweight = getfieldvalue(options,'fontweight','n');
+fontsize   = getfieldvalue(options,'scaleruler_fontsize',16);
 
 %Go through structure and fill missing arguments
@@ -14,48 +16,61 @@
 end
 
-%retrieve north arrow parameters
-x0=structure(1);
-y0=structure(2);
-lengthscale=structure(3);
-widthscale=structure(4);
-numberofticks=structure(5);
+%retrieve scale parameters
+x0            = structure(1);
+y0            = structure(2);
+lengthscale   = structure(3);
+widthscale    = structure(4);
+numberofticks = structure(5);
 
-%initialize some coordinates
-unitlength=lengthscale/(numberofticks -1);
-flag=-1;
+%If only one tick, just draw a rectangle
+if numberofticks==1,
+	text(x0+lengthscale/2,y0+2*widthscale,2,[num2str(lengthscale/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);
+else
+	%initialize some coordinates
+	unitlength=lengthscale/(numberofticks -1);
+	flag=-1;
 
-Bd=[x0 y0];
-Bu=[x0 y0+widthscale];
-Tick=0;
-
-%Text
-xt=Bu(1);
-yt=Bu(2)+widthscale;
-text(xt,yt,num2str(Tick),'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
-
-%loope over the patches
-for i=1:numberofticks-1,
-	Au=Bu;
-	Ad=Bd;
-	Bu=[Au(1)+unitlength Ad(2)+widthscale];
-	Bd=[Ad(1)+unitlength Ad(2)];
-	Tick=Tick+unitlength;
-
-	%pathes
-	if flag==-1
-		p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],'Black','FaceAlpha',0.5);
-	else
-		p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],'White','FaceAlpha',0.3);
-	end
-
-	%flip flag
-	flag=-flag;
+	Bd=[x0 y0];
+	Bu=[x0 y0+widthscale];
+	Tick=0;
 
 	%Text
 	xt=Bu(1);
 	yt=Bu(2)+widthscale;
-	if i~=numberofticks-1,
-		text(xt,yt,num2str(round_ice(Tick/1000,3)),'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
+	text(xt,yt,2,num2str(Tick),'FontSize',fontsize,'FontWeight',fontweight,'Color',fontcolor,'HorizontalAlignment','center','VerticalAlignment','baseline');
+
+	%loope over the patches
+	for i=1:numberofticks-1,
+		Au=Bu;
+		Ad=Bd;
+		Bu=[Au(1)+unitlength Ad(2)+widthscale];
+		Bd=[Ad(1)+unitlength Ad(2)];
+		Tick=Tick+unitlength;
+
+		%pathes
+		if flag==-1
+			p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],2*ones(1,4),'Black');
+		else
+			p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],2*ones(1,4),'White');
+		end
+
+		%flip flag
+		flag=-flag;
+
+		%Text
+		xt=Bu(1);
+		yt=Bu(2)+widthscale;
+		if i~=numberofticks-1,
+			text(xt,yt,2,num2str(round_ice(Tick/1000,3)),'FontSize',fontsize,'FontWeight',fontweight,'Color',fontcolor,'HorizontalAlignment','center','VerticalAlignment','baseline');
+		end
 	end
+	text(xt,yt,2,num2str(round_ice(Tick/1000,3)),'FontSize',fontsize,'FontWeight',fontweight,'Color',fontcolor,'HorizontalAlignment','center','VerticalAlignment','baseline');
+	% add leading spaces depending on length of label string
+	str=' km';
+	for i=1:numel(num2str(round_ice(Tick/1000,3))),
+		str=[' ' str];
+	end
+	text(xt,yt,2,str,'FontSize',fontsize,'FontWeight',fontweight,'Color',fontcolor,'HorizontalAlignment','left','VerticalAlignment','baseline');
 end
-text(xt,yt,[num2str(round_ice(Tick/1000,3)) ' km'],'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
Index: /issm/trunk/src/m/plot/subplotmodel.m
===================================================================
--- /issm/trunk/src/m/plot/subplotmodel.m	(revision 15395)
+++ /issm/trunk/src/m/plot/subplotmodel.m	(revision 15396)
@@ -7,6 +7,12 @@
 %Regular subplot
 if ~exist(options,'tightsubplot')
-	subplot(nlines,ncols,num);
-	return;
+	if exist(options,'asymsubplot')
+		id=getfieldvalue(options,'asymsubplot',num);
+		subplot(nlines,ncols,id);
+		return
+	else
+		subplot(nlines,ncols,num);
+		return;
+	end
 end
 
Index: /issm/trunk/src/m/plot/vim.m
===================================================================
--- /issm/trunk/src/m/plot/vim.m	(revision 15396)
+++ /issm/trunk/src/m/plot/vim.m	(revision 15396)
@@ -0,0 +1,3 @@
+function vim(index,x,y,field)
+
+trisurf(index,x,y,field),view(2),shading interp, colorbar;
Index: /issm/trunk/src/m/solve/WriteData.m
===================================================================
--- /issm/trunk/src/m/solve/WriteData.m	(revision 15395)
+++ /issm/trunk/src/m/solve/WriteData.m	(revision 15396)
@@ -24,8 +24,19 @@
 format  = getfieldvalue(options,'format');
 mattype = getfieldvalue(options,'mattype',0);    %only required for matrices
+forcinglength = getfieldvalue(options,'forcinglength',-1);
 
 %Process sparse matrices
 if issparse(data),
 	data=full(data);
+end
+
+%Scale data if necesarry
+if exist(options,'scale'),
+	scale = getfieldvalue(options,'scale');
+	if size(data,1)==forcinglength,
+		data(1:end-1,:) = scale.*data(1:end-1,:);
+	else
+		data  = scale.*data;
+	end
 end
 
Index: /issm/trunk/src/m/solve/WriteData.py
===================================================================
--- /issm/trunk/src/m/solve/WriteData.py	(revision 15395)
+++ /issm/trunk/src/m/solve/WriteData.py	(revision 15396)
@@ -35,4 +35,5 @@
 	format  = options.getfieldvalue('format')
 	mattype = options.getfieldvalue('mattype',0)    #only required for matrices
+	forcinglength = options.getfieldvalue('forcinglength',-1)
 
 	#Process sparse matrices
@@ -40,4 +41,16 @@
 #		data=full(data);
 #	end
+
+	#Scale data if necesarry
+	if options.exist('scale'):
+		scale = options.getfieldvalue('scale')
+		if numpy.size(data) > 1 :
+			if numpy.size(data,0)==forcinglength:
+				data=numpy.array(data)
+				data[0:-1,:] = scale*data[0:-1,:]
+			else:
+				data  = scale*data
+		else:
+			data  = scale*data
 
 	#Step 1: write the enum to identify this record uniquely
Index: /issm/trunk/src/m/solve/loadresultsfromcluster.m
===================================================================
--- /issm/trunk/src/m/solve/loadresultsfromcluster.m	(revision 15395)
+++ /issm/trunk/src/m/solve/loadresultsfromcluster.m	(revision 15396)
@@ -51,5 +51,5 @@
 	else
 		delete([md.miscellaneous.name '.bin']);
-		delete([md.miscellaneous.name '.petsc']);
+		delete([md.miscellaneous.name '.toolkits']);
 		if ~ispc(),
 			delete([md.miscellaneous.name '.queue']);
Index: /issm/trunk/src/m/solve/loadresultsfromcluster.py
===================================================================
--- /issm/trunk/src/m/solve/loadresultsfromcluster.py	(revision 15395)
+++ /issm/trunk/src/m/solve/loadresultsfromcluster.py	(revision 15396)
@@ -52,5 +52,5 @@
 		else:
 			os.remove(md.miscellaneous.name+'.bin')
-			os.remove(md.miscellaneous.name+'.petsc')
+			os.remove(md.miscellaneous.name+'.toolkits')
 			if not ispc():
 				os.remove(md.miscellaneous.name+'.queue')
Index: /issm/trunk/src/m/solve/marshall.m
===================================================================
--- /issm/trunk/src/m/solve/marshall.m	(revision 15395)
+++ /issm/trunk/src/m/solve/marshall.m	(revision 15396)
@@ -25,5 +25,5 @@
 
 	%Some properties do not need to be marshalled
-	if ismember(field,{'results' 'radaroverlay' 'solver' 'cluster'  'flaim' 'private'}),
+	if ismember(field,{'results' 'radaroverlay' 'toolkits' 'cluster'  'flaim' 'private'}),
 		continue;
 	end
@@ -36,5 +36,5 @@
 	%Marshall current object
 	%disp(['marshalling ' field '...']);
-	marshall(md.(field),fid);
+	marshall(md.(field),md,fid);
 end
 
Index: /issm/trunk/src/m/solve/marshall.py
===================================================================
--- /issm/trunk/src/m/solve/marshall.py	(revision 15395)
+++ /issm/trunk/src/m/solve/marshall.py	(revision 15396)
@@ -31,5 +31,5 @@
 
 		#Some properties do not need to be marshalled
-		if field in ['results','radaroverlay','solver','cluster','flaim','private']:
+		if field in ['results','radaroverlay','toolkits','cluster','flaim','private']:
 			continue
 
@@ -40,5 +40,5 @@
 		#Marshall current object
 		#print "marshalling %s ..." % field
-		exec("md.%s.marshall(fid)" % field)
+		exec("md.%s.marshall(md,fid)" % field)
 
 	#close file
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.m
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 15395)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 15396)
@@ -42,5 +42,10 @@
 
 	%read next result
-	result=ReadData(fid);
+	try,
+		result=ReadData(fid);
+	catch me,
+		disp('WARNING: file corrupted, results partial recovery');
+		result=[];
+	end
 
 end
@@ -124,5 +129,10 @@
 
 	%read next result
-	result=ReadData(fid);
+	try,
+		result=ReadData(fid);
+	catch me,
+		disp('WARNING: file corrupted, results partial recovery');
+		result=[];
+	end
 
 end
@@ -163,8 +173,35 @@
 	end
 
+	%Process units here FIXME: this should not be done here!
+	yts=365.0*24.0*3600.0;
+	if strcmp(fieldname,'BalancethicknessThickeningRate'),
+		field = field*yts;
+	elseif strcmp(fieldname,'Time'),
+		field = field/yts;
+	elseif strcmp(fieldname,'HydrologyWaterVx'),
+		field = field*yts;
+	elseif strcmp(fieldname,'HydrologyWaterVy'),
+		field = field*yts;
+	elseif strcmp(fieldname,'Vx'),
+		field = field*yts;
+	elseif strcmp(fieldname,'Vy'),
+		field = field*yts;
+	elseif strcmp(fieldname,'Vz'),
+		field = field*yts;
+	elseif strcmp(fieldname,'Vel'),
+		field = field*yts;
+	elseif strcmp(fieldname,'BasalforcingsMeltingRate'),
+		field = field*yts;
+	elseif strcmp(fieldname,'TotalSmb'),
+		field = field/10.^12*yts; %(GigaTon/year)
+	elseif strcmp(fieldname,'SurfaceforcingsMassBalance'),
+		field = field*yts;
+	end
+
 	result.fieldname=fieldname;
 	result.time=time;
 	result.step=step;
 	result.field=field;
+
 end
 % }}}
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.py
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 15395)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 15396)
@@ -66,5 +66,4 @@
 	return results
 	# }}}
-
 def parseresultsfromdiskiosplit(filename):    # {{{
 	"""
@@ -155,5 +154,4 @@
 	return results
 	# }}}
-
 def ReadData(fid):    # {{{
 	"""
@@ -187,4 +185,29 @@
 			raise TypeError("cannot read data of type %d" % type)
 
+		#Process units here FIXME: this should not be done here!
+		yts=365.0*24.0*3600.0
+		if strcmp(fieldname,'BalancethicknessThickeningRate'):
+			field = field*yts
+		elif strcmp(fieldname,'Time'):
+			field = field/yts
+		elif strcmp(fieldname,'HydrologyWaterVx'):
+			field = field*yts
+		elif strcmp(fieldname,'HydrologyWaterVy'):
+			field = field*yts
+		elif strcmp(fieldname,'Vx'):
+			field = field*yts
+		elif strcmp(fieldname,'Vy'):
+			field = field*yts
+		elif strcmp(fieldname,'Vz'):
+			field = field*yts
+		elif strcmp(fieldname,'Vel'):
+			field = field*yts
+		elif strcmp(fieldname,'BasalforcingsMeltingRate'):
+			field = field*yts
+		elif strcmp(fieldname,'TotalSmb'):
+			field = field/10.**12.*yts #(GigaTon/year)
+		elif strcmp(fieldname,'SurfaceforcingsMassBalance'):
+			field = field*yts
+
 		result=OrderedDict()
 		result['fieldname']=fieldname
@@ -198,5 +221,4 @@
 	return result
 	# }}}
-
 def ReadDataDimensions(fid):    # {{{
 	"""
@@ -240,3 +262,2 @@
 	return result
 	# }}}
-
Index: /issm/trunk/src/m/solve/process_solve_options.m
===================================================================
--- /issm/trunk/src/m/solve/process_solve_options.m	(revision 15395)
+++ /issm/trunk/src/m/solve/process_solve_options.m	(revision 15396)
@@ -11,6 +11,6 @@
 if ~ismember(solution_type,[DiagnosticSolutionEnum(),PrognosticSolutionEnum(),ThermalSolutionEnum(),...
 		SteadystateSolutionEnum(),TransientSolutionEnum(),EnthalpySolutionEnum(),...
-		BalancethicknessSolutionEnum(),WeakBalancethicknessSolutionEnum(),BedSlopeSolutionEnum(),...
-		SurfaceSlopeSolutionEnum(),HydrologySolutionEnum(),FlaimSolutionEnum()]),
+		BalancethicknessSolutionEnum(),BalancethicknessSoftSolutionEnum(),BedSlopeSolutionEnum(),...
+		SurfaceSlopeSolutionEnum(),HydrologySolutionEnum(),FlaimSolutionEnum(),GiaSolutionEnum()]),
 	error(['process_solve_options error message: solution_type ' EnumToString(solution_type) ' not supported yet!']);
 end
Index: /issm/trunk/src/m/solve/process_solve_options.py
===================================================================
--- /issm/trunk/src/m/solve/process_solve_options.py	(revision 15395)
+++ /issm/trunk/src/m/solve/process_solve_options.py	(revision 15396)
@@ -20,5 +20,6 @@
 	if solution_type not in (DiagnosticSolutionEnum(),PrognosticSolutionEnum(),ThermalSolutionEnum(),\
 			SteadystateSolutionEnum(),TransientSolutionEnum(),EnthalpySolutionEnum(),\
-			BalancethicknessSolutionEnum(),BedSlopeSolutionEnum(),SurfaceSlopeSolutionEnum(),HydrologySolutionEnum(),FlaimSolutionEnum()):
+			BalancethicknessSolutionEnum(),BedSlopeSolutionEnum(),SurfaceSlopeSolutionEnum(),\
+			HydrologySolutionEnum(),FlaimSolutionEnum(),GiaSolutionEnum()):
 		raise ValueError("process_solve_options error message: solution_type '%s' not supported yet!" % EnumToString(solution_type)[0])
 	outoptions['solution_type']=solution_type
Index: /issm/trunk/src/m/solve/solve.m
===================================================================
--- /issm/trunk/src/m/solve/solve.m	(revision 15395)
+++ /issm/trunk/src/m/solve/solve.m	(revision 15396)
@@ -68,13 +68,7 @@
 end
 
-%we need to make sure we have PETSC support, otherwise, we run with only one cpu: 
-if ~ispetsc(),
-	disp('PETSc support not included, running on 1 cpu only!');
-	cluster.np=1;
-end
-
 %Write all input files
 marshall(md);                                          % bin file
-PetscFile(md.solver,[md.miscellaneous.name '.petsc']); % petsc file
+ToolkitsFile(md.toolkits,[md.miscellaneous.name '.toolkits']); % toolkits file
 BuildQueueScript(cluster,md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof); % queue file
 
@@ -88,5 +82,11 @@
 %Launch job
 modelname = md.miscellaneous.name;
-filelist  = {[modelname '.bin '] [modelname '.petsc '] [modelname '.queue ']};
+filelist  = {[modelname '.bin '] [modelname '.toolkits ']};
+if ispc,
+	filelist{end+1}=[modelname '.bat '];
+else
+	filelist{end+1}=[modelname '.queue '];
+end
+
 if md.qmu.isdakota,
 	filelist{end+1} = [modelname '.qmu.in'];
@@ -101,13 +101,20 @@
 
 %wait on lock
-if md.settings.waitonlock>0,
-	%we wait for the done file
-	islock=waitonlock(md);
-	if islock==0, %no results to be loaded
-		disp('The results must be loaded manually with md=loadresultsfromcluster(md).');
-	else          %load results
-		disp('loading results from cluster');
+if isnan(md.settings.waitonlock),
+	%load when user enters 'y'
+	disp('solution launched on remote cluster. log in to detect job completion.');
+	choice=input('Is the job successfully completed? (y/n)','s');
+	if ~strcmp(choice,'y'), 
+		disp('Results not loaded... exiting'); 
+	else
 		md=loadresultsfromcluster(md);
 	end
+elseif md.settings.waitonlock>0,
+	%we wait for the done file
+	done=waitonlock(md);
+	disp('loading results from cluster');
+	md=loadresultsfromcluster(md);
+elseif md.settings.waitonlock==0,
+	 disp('Model results must be loaded manually with md=loadresultsfromcluster(md);');
 end
 
Index: /issm/trunk/src/m/solve/solve.py
===================================================================
--- /issm/trunk/src/m/solve/solve.py	(revision 15395)
+++ /issm/trunk/src/m/solve/solve.py	(revision 15396)
@@ -80,11 +80,6 @@
 	#Write all input files
 	marshall(md)                                           # bin file
-	md.solver.PetscFile(md.miscellaneous.name+'.petsc')    # petsc file
+	md.toolkits.ToolkitsFile(md.miscellaneous.name+'.toolkits')    # toolkits file
 	cluster.BuildQueueScript(md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof)    # queue file
-
-	#we need to make sure we have PETSC support, otherwise, we run with only one cpu: 
-	if not ispetsc():
-		print "PETSC support not included, running on 1 cpu only!"
-		cluster.np=1
 
 	#Stop here if batch mode
@@ -96,5 +91,5 @@
 	#Launch job
 	modelname = md.miscellaneous.name
-	filelist  = [modelname+'.bin ',modelname+'.petsc ',modelname+'.queue ']
+	filelist  = [modelname+'.bin ',modelname+'.toolkits ',modelname+'.queue ']
 	if md.qmu.isdakota:
 		filelist.append(modelname+'.qmu.in')
Index: /issm/trunk/src/m/solve/waitonlock.m
===================================================================
--- /issm/trunk/src/m/solve/waitonlock.m	(revision 15395)
+++ /issm/trunk/src/m/solve/waitonlock.m	(revision 15396)
@@ -1,6 +1,8 @@
-function flag=waitonlock(md)
+function ispresent=waitonlock(md)
 %WAITONLOCK - wait for a file
 %
-%   This routine will return when a file named 'filename' is written to disk.
+%   This routine will return when a file named 'lockfilename' is written to disk.
+%   Also check for outlog file be cause it might bewritten several seconds
+%   after the lock file.
 %   If the time limit given in input is exceeded, return 0
 %
@@ -8,53 +10,58 @@
 %      flag=waitonlock(md)
 
-%Get filename (lock file) and options
-executionpath=md.cluster.executionpath;
-cluster=md.cluster.name;
-login=md.cluster.login;
-if isprop(md.cluster,'port') 
-	port=md.cluster.port;
+%Return if waitonlock < 0 (no need to wait)
+
+%Get lockfilename (lock file) and options
+executionpath = md.cluster.executionpath;
+timelimit     = md.settings.waitonlock;
+cluster       = md.cluster;
+lockfilename  = [executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.lock'];
+logfilename   = [executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.outlog'];
+
+%If we are using the generic cluster in interactive mode, job is already complete
+if isa(cluster,'generic') & cluster.interactive
+	%We are in interactive mode, no need to check for job completion
+	ispresent=1;
+	return;
 end
-timelimit=md.settings.waitonlock;
-filename=[executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.lock'];
 
-%waitonlock will work if the lock is on the same machine only: 
-if ~strcmpi(oshostname(),cluster),
+%initialize time and file presence test flag
+time=0; ispresent=0; time0=clock;
+disp(['waiting for ' lockfilename ' hold on... (Ctrl+C to exit)'])
 
-	disp('solution launched on remote cluster. log in to detect job completion.');
-	choice=input('Is the job successfully completed? (y/n)','s');
-	if ~strcmp(choice,'y'), 
-		disp('Results not loaded... exiting'); 
-		flag=0;
+%prepare command if the job is not running on the local machine
+if ~strcmpi(oshostname(),cluster.name),
+	login = cluster.login;
+	port  = 0;
+	if isprop(cluster,'port') 
+		port = cluster.port;
+	end
+	if port,
+		command = ['ssh -l ' login ' -p ' num2str(port) ' localhost "[ -f ' lockfilename ' ] && [ -f ' logfilename ' ]" 2>/dev/null'];
 	else
-		flag=1;
-	end
-
-%job is running on the same machine
-else
-
-	if ismember('interactive',properties(md.cluster)) & md.cluster.interactive
-		%We are in interactive mode, no need to check for job completion
-		flag=1;
-		return;
-	end
-	%initialize time and file presence test flag
-	time=0; ispresent=0;
-	disp(['waiting for ' filename ' hold on... (Ctrl+C to exit)'])
-
-	%loop till file .lock exist or time is up
-	while (ispresent==0 & time<timelimit)
-		ispresent=exist(filename,'file');
-		pause(1);
-		time=time+1/60;
-	end
-
-	%build output
-	if (time>timelimit),
-		disp('Time limit exceeded. Increase md.settings.waitonlock');
-		disp('The results must be loaded manually with md=loadresultsfromcluster(md).');
-		error(['waitonlock error message: time limit exceeded']);
-		flag=0;
-	else
-		flag=1;
+		command = ['ssh -l ' login ' ' cluster.name ' "[ -f ' lockfilename ' ] && [ -f ' logfilename ' ]" 2>/dev/null'];
 	end
 end
+
+%loop till file .lock exist or time is up
+while (ispresent==0 & time<timelimit)
+	if strcmpi(oshostname(),cluster.name),
+		pause(1);
+		ispresent=(exist(lockfilename,'file') & exist(logfilename,'file'));
+		time=etime(clock,time0)/60;
+	else
+		pause(10);
+		time=etime(clock,time0);
+		fprintf('\rchecking for job completion (time: %i min %i sec)      ',floor(time/60),floor(rem(time,60)));
+		time=time/60; %converts time from sec to min
+		ispresent=~system(command);
+		if ispresent, fprintf('\n'); end
+	end
+end
+
+%build output
+if (time>timelimit),
+	disp('Time limit exceeded. Increase md.settings.waitonlock');
+	disp('The results must be loaded manually with md=loadresultsfromcluster(md).');
+	error(['waitonlock error message: time limit exceeded']);
+end
Index: /issm/trunk/src/m/solvers/asmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/asmoptions.m	(revision 15395)
+++ /issm/trunk/src/m/solvers/asmoptions.m	(revision 15396)
@@ -10,4 +10,5 @@
 
 %default asm options
+asm.toolkit='petsc';
 asm.mat_type=getfieldvalue(options,'mat_type','aij');
 asm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
Index: /issm/trunk/src/m/solvers/asmoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/asmoptions.py	(revision 15395)
+++ /issm/trunk/src/m/solvers/asmoptions.py	(revision 15396)
@@ -12,5 +12,5 @@
 	arguments=pairoptions(*args) 
 	
-	options=[['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','lu'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-30]];
+	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','lu'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-30]];
 
 	#now, go through our arguments, and write over default options.
Index: /issm/trunk/src/m/solvers/iluasmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/iluasmoptions.m	(revision 15395)
+++ /issm/trunk/src/m/solvers/iluasmoptions.m	(revision 15396)
@@ -10,4 +10,5 @@
 
 %default iluasm options
+iluasm.toolkit='petsc';
 iluasm.mat_type=getfieldvalue(options,'mat_type','aij');
 iluasm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
Index: /issm/trunk/src/m/solvers/iluasmoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/iluasmoptions.py	(revision 15395)
+++ /issm/trunk/src/m/solvers/iluasmoptions.py	(revision 15396)
@@ -15,4 +15,5 @@
 
 	#default iluasm options
+	iluasm['toolkit']='petsc'
 	iluasm['mat_type']=options.getfieldvalue('mat_type','aij')
 	iluasm['ksp_type']=options.getfieldvalue('ksp_type','gmres')
Index: /issm/trunk/src/m/solvers/issmsolver.m
===================================================================
--- /issm/trunk/src/m/solvers/issmsolver.m	(revision 15396)
+++ /issm/trunk/src/m/solvers/issmsolver.m	(revision 15396)
@@ -0,0 +1,14 @@
+function issmoptions=issmsolver(varargin)
+%ISSMSOLVER - 
+%
+%   Usage:
+%      options=issmsolver;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+issmoptions=struct();
+
+%default issmoptions options
+issmoptions.toolkit='issm';
+issmoptions.mat_type=getfieldvalue(options,'mat_type','mpidense');
+issmoptions.vec_type=getfieldvalue(options,'vec_type','mpi');
Index: /issm/trunk/src/m/solvers/issmsolver.py
===================================================================
--- /issm/trunk/src/m/solvers/issmsolver.py	(revision 15396)
+++ /issm/trunk/src/m/solvers/issmsolver.py	(revision 15396)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def asmoptions(*args):
+	#ISSMSOLVE - return issm solver options
+	#
+	#   Usage:
+	#      options=issmsolver;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['toolkit','issm'],['mat_type','mpidense'],['vec_type','mpi']];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/trunk/src/m/solvers/jacobiasmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/jacobiasmoptions.m	(revision 15395)
+++ /issm/trunk/src/m/solvers/jacobiasmoptions.m	(revision 15396)
@@ -10,4 +10,5 @@
 
 %default jacobiasm options
+jacobiasm.toolkit='petsc';
 jacobiasm.mat_type=getfieldvalue(options,'mat_type','aij');
 jacobiasm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
Index: /issm/trunk/src/m/solvers/jacobiasmoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/jacobiasmoptions.py	(revision 15395)
+++ /issm/trunk/src/m/solvers/jacobiasmoptions.py	(revision 15396)
@@ -12,5 +12,5 @@
 	arguments=pairoptions(*args) 
 	
-	options=[['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','jacobi'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-15]];
+	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','jacobi'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-15]];
 
 	#now, go through our arguments, and write over default options.
Index: /issm/trunk/src/m/solvers/jacobicgoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/jacobicgoptions.m	(revision 15395)
+++ /issm/trunk/src/m/solvers/jacobicgoptions.m	(revision 15396)
@@ -10,4 +10,5 @@
 
 %default jacobiasm options
+jacobicg.toolkit='petsc';
 jacobicg.mat_type=getfieldvalue(options,'mat_type','aij');
 jacobicg.ksp_type=getfieldvalue(options,'ksp_type','cg');
Index: /issm/trunk/src/m/solvers/jacobicgoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/jacobicgoptions.py	(revision 15395)
+++ /issm/trunk/src/m/solvers/jacobicgoptions.py	(revision 15396)
@@ -12,5 +12,5 @@
 	arguments=pairoptions(*args) 
 	
-	options=[['mat_type','aij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]];
+	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]];
 
 	#now, go through our arguments, and write over default options.
Index: /issm/trunk/src/m/solvers/matlaboptions.m
===================================================================
--- /issm/trunk/src/m/solvers/matlaboptions.m	(revision 15395)
+++ /issm/trunk/src/m/solvers/matlaboptions.m	(revision 15396)
@@ -10,3 +10,4 @@
 
 %default matlab options
+maltab.toolkit='petsc';
 maltab.ksp_type='matlab';
Index: /issm/trunk/src/m/solvers/matlaboptions.py
===================================================================
--- /issm/trunk/src/m/solvers/matlaboptions.py	(revision 15395)
+++ /issm/trunk/src/m/solvers/matlaboptions.py	(revision 15396)
@@ -12,5 +12,5 @@
 	arguments=pairoptions(*args) 
 	
-	options=[['ksp_type','matlab']];
+	options=[['toolkit','petsc'],['ksp_type','matlab']];
 
 	#now, go through our arguments, and write over default options.
Index: /issm/trunk/src/m/solvers/mumpsoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/mumpsoptions.m	(revision 15395)
+++ /issm/trunk/src/m/solvers/mumpsoptions.m	(revision 15396)
@@ -12,4 +12,5 @@
 PETSC_VERSION=petscversion();
 if PETSC_VERSION==2,
+	mumps.toolkit='petsc';
 	mumps.mat_type=getfieldvalue(options,'mat_type','aijmumps');
 	mumps.ksp_type=getfieldvalue(options,'ksp_type','preonly');
@@ -19,4 +20,5 @@
 end
 if PETSC_VERSION==3,
+	mumps.toolkit='petsc';
 	mumps.mat_type=getfieldvalue(options,'mat_type','mpiaij');
 	mumps.ksp_type=getfieldvalue(options,'ksp_type','preonly');
Index: /issm/trunk/src/m/solvers/mumpsoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/mumpsoptions.py	(revision 15395)
+++ /issm/trunk/src/m/solvers/mumpsoptions.py	(revision 15396)
@@ -18,4 +18,5 @@
 	PETSC_VERSION=petscversion()
 	if PETSC_VERSION==2:
+		mumps['toolkit']='petsc'
 		mumps['mat_type']=options.getfieldvalue('mat_type','aijmumps')
 		mumps['ksp_type']=options.getfieldvalue('ksp_type','preonly')
@@ -24,4 +25,5 @@
 		mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')
 	if PETSC_VERSION==3:
+		mumps['toolkit']='petsc'
 		mumps['mat_type']=options.getfieldvalue('mat_type','mpiaij')
 		mumps['ksp_type']=options.getfieldvalue('ksp_type','preonly')
Index: /issm/trunk/src/m/solvers/soroptions.m
===================================================================
--- /issm/trunk/src/m/solvers/soroptions.m	(revision 15395)
+++ /issm/trunk/src/m/solvers/soroptions.m	(revision 15396)
@@ -10,4 +10,5 @@
 
 %default sor options
+sor.toolkit='petsc';
 sor.mat_type=getfieldvalue(options,'mat_type','aij');
 sor.ksp_type=getfieldvalue(options,'ksp_type','cg');
Index: /issm/trunk/src/m/solvers/soroptions.py
===================================================================
--- /issm/trunk/src/m/solvers/soroptions.py	(revision 15395)
+++ /issm/trunk/src/m/solvers/soroptions.py	(revision 15396)
@@ -12,5 +12,5 @@
 	arguments=pairoptions(*args) 
 	
-	options=[['mat_type','aij'],['ksp_type','cg'],['pc_type','sor'],['pc_sor_omega',1.1],['pc_sor_its',2]];
+	options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','cg'],['pc_type','sor'],['pc_sor_omega',1.1],['pc_sor_its',2]];
 
 	#now, go through our arguments, and write over default options.
Index: /issm/trunk/src/m/solvers/stokesoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/stokesoptions.m	(revision 15395)
+++ /issm/trunk/src/m/solvers/stokesoptions.m	(revision 15396)
@@ -15,4 +15,5 @@
 end
 if PETSC_VERSION==3,
+	stokes.toolkit='petsc';
 	stokes.mat_type=getfieldvalue(options,'mat_type','mpiaij');
 	stokes.ksp_max_it=getfieldvalue(options,'ksp_max_it',1000);
Index: /issm/trunk/src/m/solvers/stokesoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/stokesoptions.py	(revision 15395)
+++ /issm/trunk/src/m/solvers/stokesoptions.py	(revision 15396)
@@ -19,5 +19,5 @@
 		raise RuntimeError('stokesoptions error message: multi-physics options not supported in Petsc 2')
 	if PETSC_VERSION==3:
-		options=[['mat_type','mpiaij'],['ksp_max_it',1000],['ksp_type','gmres'],['pc_type','fieldsplit'],['pc_field_split_type','schur'],\
+		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'],\
 	['fieldsplit_1_pc_type','jacobi'],['fieldsplit_1_ksp_type','preonly'],['issm_option_solver','stokes']]
Index: sm/trunk/src/m/string/issmprintf.m
===================================================================
--- /issm/trunk/src/m/string/issmprintf.m	(revision 15395)
+++ 	(revision )
@@ -1,13 +1,0 @@
-function issmprintf(flag,format,varargin)
-%ISSMPRINTF -  display string in solution sequences. wrapper to disp and sprintf.  
-%
-%   Usage:
-%      issmprintf(flag,format,string)
-%      flag can be used to switch display on and off
-%
-%   Example:
-%      issmprintf(1,'%s\n','string to display');
-
-if flag,
-	disp(sprintf(format,varargin{:}));
-end
Index: /issm/trunk/src/mobile/Makefile.am
===================================================================
--- /issm/trunk/src/mobile/Makefile.am	(revision 15396)
+++ /issm/trunk/src/mobile/Makefile.am	(revision 15396)
@@ -0,0 +1,3 @@
+if ANDROID
+SUBDIRS = native
+endif
Index: /issm/trunk/src/mobile/native/Main.cpp
===================================================================
--- /issm/trunk/src/mobile/native/Main.cpp	(revision 15396)
+++ /issm/trunk/src/mobile/native/Main.cpp	(revision 15396)
@@ -0,0 +1,194 @@
+#include "../../c/issm.h"
+#include <cstddef>
+#include <stdio.h>
+
+//Android specific header includes: 
+#include <jni.h>
+#include <android/log.h>
+#include <android/log.h>
+
+//iOS specific header includes: 
+
+namespace gov_nasa_jpl_issm
+{
+	/*Global variables{{{*/
+	FemModel *fm;
+	double* xyz; /*keep vertices information here*/
+	/*}}}*/
+	jint Initialize(JNIEnv *env, jclass clazz, jstring jsolution_type, jstring jabsfile, jstring jrelfile) /*{{{*/
+	{
+		
+		/*arguments to constructor: */
+		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;
+
+		/*log:*/
+		__android_log_print(ANDROID_LOG_INFO, "Native","Initializing FemModel");
+
+		/*retrieve from java machine: */
+		solution_type = (char*)env->GetStringUTFChars(jsolution_type,0);
+		absfile = (char*)env->GetStringUTFChars(jabsfile,0);
+		relfile = (char*)env->GetStringUTFChars(jrelfile,0);
+
+		/*creat arguments to call constructor for FemModel: */
+		argc=4; 
+		argv=(char**)malloc(argc*sizeof(char*));
+		argv[0]=(char*)issmname;
+		argv[1]=solution_type;
+		argv[2]=absfile;
+		argv[3]=relfile;
+		
+		/*call Model constructor passing in infile as File Descriptor parameter.*/
+		fm  = new FemModel(argc,argv,communicator);
+
+		/*we'll need the toolkits activated right away to use matrices: */
+		ToolkitsOptionsFromAnalysis(fm->parameters,NoneAnalysisEnum);
+
+		/*release strings: */
+		env->ReleaseStringUTFChars(jsolution_type, solution_type); //must realease the char*
+		env->ReleaseStringUTFChars(jabsfile, absfile); //must realease the char*
+		env->ReleaseStringUTFChars(jrelfile, relfile); //must realease the char*
+
+		/*figure out size of solution: */
+		__android_log_print(ANDROID_LOG_INFO, "Native","Number of elements");
+		jint size = (jint) fm->elements->NumberOfElements();
+
+		/*retrieve vertices x,y and z coordinates: */
+		__android_log_print(ANDROID_LOG_INFO, "Native","Retrieving vertices");
+		xyz=fm->vertices->ToXYZ();
+		
+		/*log: */
+		__android_log_print(ANDROID_LOG_INFO, "Native","Done Initializing FemModel");
+
+		return size;
+
+	}
+	/*}}}*/
+	void Solve(JNIEnv *env, jclass clazz , jdouble alpha, jdouble temperature, jobject buf){ /*{{{*/
+
+		int i,count;
+		double x1,y1,z1,vel1;
+		double x2,y2,z2,vel2;
+		double x3,y3,z3,vel3;
+		int    v1,v2,v3,eid;
+		Patch* patch=NULL;
+		
+		/*log:*/
+		__android_log_print(ANDROID_LOG_INFO, "Native","Solving ");
+
+		/*retrieve buffer: */
+		jdouble *dBuf = (jdouble *)env->GetDirectBufferAddress(buf);
+
+		/*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);
+
+		InputDuplicatex(fm->elements,fm->nodes,fm->vertices,fm->loads,fm->materials,fm->parameters,AndroidFrictionCoefficientEnum,FrictionCoefficientEnum);
+
+		/*now scale friction by alpha: */
+		InputScalex(fm->elements,fm->nodes,fm->vertices,fm->loads,fm->materials,fm->parameters,FrictionCoefficientEnum,alpha/100);
+
+		/*solve: */
+		fm -> Solve();
+
+		/*retrieve results: */
+		__android_log_print(ANDROID_LOG_INFO, "Native","Retrieving results ");
+		fm->elements->ProcessResultsUnits();
+		patch=fm->elements->ResultsToPatch();
+
+		/*sort out the velocities: */
+		for(i=0;i<patch->numrows;i++){
+			if ((patch->values[i*patch->numcols+0])==VelEnum){
+
+				/*Each row of the Patch object is made of the following information: 
+				  - the result enum_type, 
+				  - the step and time, 
+				  - the id of the element, 
+				  - the interpolation type, 
+				  - the vertices ids, 
+				  - and the values at the nodes (could be different from the vertices)
+				*/
+				eid=(int)patch->values[i*patch->numcols+3]-1;
+				v1=(int)patch->values[i*patch->numcols+5]; 
+				x1=xyz[3*(v1-1)+0]; y1=xyz[3*(v1-1)+1]; z1=xyz[3*(v1-1)+2];
+				
+				v2=(int)patch->values[i*patch->numcols+6];
+				x2=xyz[3*(v2-1)+0]; y2=xyz[3*(v2-1)+1]; z2=xyz[3*(v2-1)+2];
+				
+				v3=(int)patch->values[i*patch->numcols+7];
+				x3=xyz[3*(v3-1)+0]; y3=xyz[3*(v3-1)+1]; z3=xyz[3*(v3-1)+2];
+
+				vel1=patch->values[i*patch->numcols+8]; 
+				vel2=patch->values[i*patch->numcols+9]; 
+				vel3=patch->values[i*patch->numcols+10]; 
+
+				/*plug into dBuf: */
+				/*vertex 1: */
+				dBuf[12*eid+0]=x1;
+				dBuf[12*eid+1]=y1;
+				dBuf[12*eid+2]=z1;
+
+				/*vertex 2: */
+				dBuf[12*eid+3]=x2;
+				dBuf[12*eid+4]=y2;
+				dBuf[12*eid+5]=z2;
+			
+				/*vertex 3: */
+				dBuf[12*eid+6]=x3;
+				dBuf[12*eid+7]=y3;
+				dBuf[12*eid+8]=z3;
+				
+				/*values at 3 vertices: */
+				dBuf[12*eid+9]=vel1;
+				dBuf[12*eid+10]=vel2;
+				dBuf[12*eid+11]=vel3;
+
+			}
+		}
+
+		/*for(i=0;i<148;i++){
+		__android_log_print(ANDROID_LOG_INFO, "Native","%g %g %g | %g %g %g | %g %g %g | %g %g %g\n",
+				dBuf[12*i+0],dBuf[12*i+1],dBuf[12*i+2],
+				dBuf[12*i+3],dBuf[12*i+4],dBuf[12*i+5],
+				dBuf[12*i+6],dBuf[12*i+7],dBuf[12*i+8],
+				dBuf[12*i+9],dBuf[12*i+10],dBuf[12*i+11]);
+		}*/
+
+		/*delete temporary data:*/
+		delete patch;
+
+	}/*}}}*/
+	static JNINativeMethod method_table[] = /*{{{*/
+	{
+			{"createISSMModel"   ,"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I"  , (void *) Initialize},
+			{"solveISSMModel", "(DDLjava/nio/DoubleBuffer;)V", (void *) Solve}
+	};
+	/*}}}*/
+}
+
+using namespace gov_nasa_jpl_issm;
+extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) /*{{{*/
+{
+    JNIEnv* env;
+    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
+        return -1;
+    }
+    else
+    {
+    	jclass clazz = env->FindClass("gov/nasa/jpl/issm/IssmJni");
+    	if(clazz)
+    	{
+    		env->RegisterNatives(clazz, method_table, 3);
+    		env->DeleteLocalRef(clazz);
+    		return JNI_VERSION_1_6;
+    	}
+    	else return -1;
+    }
+}
+/*}}}*/
Index: /issm/trunk/src/mobile/native/Makefile.am
===================================================================
--- /issm/trunk/src/mobile/native/Makefile.am	(revision 15396)
+++ /issm/trunk/src/mobile/native/Makefile.am	(revision 15396)
@@ -0,0 +1,7 @@
+#Generate JNI library
+lib_LTLIBRARIES = libIssmJni.la
+
+libIssmJni_la_SOURCES = Main.cpp
+libIssmJni_la_LIBADD = $(ISSM_DIR)/src/c/libISSMCore.a $(ISSM_DIR)/externalpackages/gsl/install/lib/libgsl.a $(ISSM_DIR)/externalpackages/gsl/install/lib/libgslcblas.a
+
+AM_LDFLAGS = -llog
Index: sm/trunk/src/perl/DiagnosticAlter.pl
===================================================================
--- /issm/trunk/src/perl/DiagnosticAlter.pl	(revision 15395)
+++ 	(revision )
@@ -1,18 +1,0 @@
-#!/usr/bin/perl
-# alter file perl script
-
-open(INFILE,  "icediagnostic_core_nonlinear.m");
-open(OUTFILE, ">icediagnostic_core_nonlinear.alt.m");
-
-
-while (<INFILE>) {
-	if(/\[K_gg,p_g\]=SystemMatrices\(elements,grids,loads,materials,kflag, pflag, sparsity,inputs,analysis_type\);/){
-		print OUTFILE "    [K_gg,p_g]=SystemMatrices(elements,grids,loads,materials,kflag, pflag, sparsity,inputs,analysis_type);\n    save systemmatrices_ice K_gg p_g; error\('debug'\);\n"
-	}
-	else{
-		print OUTFILE "$_";
-	}
-}
-
-close INFILE;
-close OUTFILE;
Index: sm/trunk/src/perl/rsp_formatter.pl
===================================================================
--- /issm/trunk/src/perl/rsp_formatter.pl	(revision 15395)
+++ 	(revision )
@@ -1,55 +1,0 @@
-#!/usr/bin/perl
-#
-#
-# write a list of object filenames to an .rsp file,
-# formatted according to tlib's input requirements
-#
-# usage:  rsp_formatter infile.rsp
-# where:  infile.rsp is a one line file consisting of
-#         object filenames
-# output: is the tlib-formatted infile.rsp
-# note:   multiple input files can be specified, e.g.
-#         rsp_formatter infile1.rsp infile2.rsp -etc.-
-
-use Fatal qw/ open /;
-use File::Basename;
-use Text::ParseWords;
-
-
-foreach (@ARGV) {
-
-#	loop (re)initialisation:
-	@words = ();
-	@new_words =();
-
-	($name,$path,$suffix) = fileparse($_,"\.rsp");
-	print "formatting $name$suffix for input to tlib...\n";
-
-#	open, read explicitly so we can treat one ARGV at a time:
-	open INFILE, "$_";
-	$line=<INFILE>;
-	close INFILE;
-	chomp($line);
-
-	@words = &parse_line('\s+', 0, $line);
-
-	$i=0;
-	foreach(@words) {
-		if ($i < $#words) {
-			push( @new_words, "+$_ &");
-		}
-		else {
-			push( @new_words, "+$_,$name");
-		}
-		$i++;
-	}
-
-	open(OUTFILE, ">$_");
-	foreach(@new_words) {
-		print OUTFILE "$_\n";
-	}
-	close(OUTFILE); 
-
-	print "...done\n";
-}
-
Index: /issm/trunk/src/wrappers/AverageFilter/AverageFilter.cpp
===================================================================
--- /issm/trunk/src/wrappers/AverageFilter/AverageFilter.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/AverageFilter/AverageFilter.cpp	(revision 15396)
@@ -13,11 +13,11 @@
 
 void AverageFilterUsage(void){/*{{{*/
-	_printLine_("   AverageFilter usage:");
-	_printLine_("   [image_out]=AverageFilter(image_in,pixels);\n");
-	_printLine_("   where:");
-	_printLine_("      image_in in double format");
-	_printLine_("      pixels: characteristic size of smoothing");
-	_printLine_("      image_out in double format");
-	_printLine_("");
+	_printf_("   AverageFilter usage:\n");
+	_printf_("   [image_out]=AverageFilter(image_in,pixels)\n");
+	_printf_("   where:\n");
+	_printf_("      image_in in double format\n");
+	_printf_("      pixels: characteristic size of smoothing\n");
+	_printf_("      image_out in double format\n");
+	_printf_("\n");
 }/*}}}*/
 WRAPPER(AverageFilter){
@@ -30,7 +30,5 @@
 	int     smooth;
 
-
 	/* output: */
-	mxArray* pfield=NULL;
 	double* imageout=NULL;
 	int     imageout_rows,imageout_cols;
@@ -45,5 +43,5 @@
 	FetchData(&imagein,&imagein_rows,&imagein_cols,IMAGEIN);
 	FetchData(&smooth,SMOOTH);
-	
+
 	/*Run core hole filler routine: */
 	AverageFilterx( &imageout,imagein,imagein_rows,imagein_cols,smooth);
@@ -52,4 +50,8 @@
 	WriteData(IMAGEOUT,imageout,imagein_rows,imagein_cols);
 
+	/*free ressources: */
+	xDelete<double>(imagein);
+	xDelete<double>(imageout);
+
 	/*end module: */
 	MODULEEND();
Index: /issm/trunk/src/wrappers/AverageFilter/AverageFilter.h
===================================================================
--- /issm/trunk/src/wrappers/AverageFilter/AverageFilter.h	(revision 15395)
+++ /issm/trunk/src/wrappers/AverageFilter/AverageFilter.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.cpp
===================================================================
--- /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.cpp	(revision 15396)
@@ -5,11 +5,11 @@
 
 void BamgConvertMeshUsage(void){/*{{{*/
-	_pprintString_("BAMGCONVERTMESH - convert [x y index] to a bamg geom and mesh geom");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [bamggeom bamgmesh]=BamgConvertMesh(index,x,y);");
-	_pprintLine_("      index: index of the mesh");
-	_pprintLine_("      x,y: coordinates of the nodes");
-	_pprintLine_("");
+	_printf0_("BAMGCONVERTMESH - convert [x y index] to a bamg geom and mesh geom");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [bamggeom bamgmesh]=BamgConvertMesh(index,x,y)\n");
+	_printf0_("      index: index of the mesh\n");
+	_printf0_("      x,y: coordinates of the nodes\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(BamgConvertMesh){
@@ -54,4 +54,7 @@
 
 	/*Clean up*/
+	xDelete<int>(index);
+	xDelete<double>(x);
+	xDelete<double>(y);
 	delete bamggeom;
 	delete bamgmesh;
Index: /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.h
===================================================================
--- /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.h	(revision 15395)
+++ /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.h	(revision 15396)
@@ -17,10 +17,9 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
-#include "../../c/io/io.h"
+#include "../../c/shared/io/io.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/BamgMesher/BamgMesher.cpp
===================================================================
--- /issm/trunk/src/wrappers/BamgMesher/BamgMesher.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/BamgMesher/BamgMesher.cpp	(revision 15396)
@@ -5,16 +5,16 @@
 
 void BamgMesherUsage(void){/*{{{*/
-	_pprintLine_("");
-	_pprintLine_("   usage: [bamgmesh,bamggeom]=" << __FUNCT__ << "(bamgmesh,bamggeom,bamgoptions);");
-	_pprintLine_("");
+	_printf0_("\n");
+	_printf0_("   usage: [bamgmesh,bamggeom]=" << __FUNCT__ << "(bamgmesh,bamggeom,bamgoptions)\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(BamgMesher){
 
 	/*Intermediary*/
-	BamgOpts *bamgopts=NULL;
-	BamgMesh *bamgmesh_in=NULL;
-	BamgGeom *bamggeom_in=NULL;
-	BamgMesh *bamgmesh_out=NULL;
-	BamgGeom *bamggeom_out=NULL;
+	BamgOpts *bamgopts     = NULL;
+	BamgMesh *bamgmesh_in  = NULL;
+	BamgGeom *bamggeom_in  = NULL;
+	BamgMesh *bamgmesh_out = NULL;
+	BamgGeom *bamggeom_out = NULL;
 
 	/*Boot module*/
Index: /issm/trunk/src/wrappers/BamgMesher/BamgMesher.h
===================================================================
--- /issm/trunk/src/wrappers/BamgMesher/BamgMesher.h	(revision 15395)
+++ /issm/trunk/src/wrappers/BamgMesher/BamgMesher.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.cpp
===================================================================
--- /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.cpp	(revision 15396)
@@ -5,11 +5,11 @@
 
 void BamgTriangulateUsage(void){/*{{{*/
-	_pprintString_("BAMGTRIANGULATE - Delaunay Triangulation of a list of points");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      index=BamgTriangulate(x,y);");
-	_pprintLine_("      index: index of the triangulation");
-	_pprintLine_("      x,y: coordinates of the nodes");
-	_pprintLine_("");
+	_printf0_("BAMGTRIANGULATE - Delaunay Triangulation of a list of points");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      index=BamgTriangulate(x,y);\n");
+	_printf0_("      index: index of the triangulation\n");
+	_printf0_("      x,y: coordinates of the nodes\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(BamgTriangulate){
@@ -20,5 +20,5 @@
 	int     x_cols;
 	int     y_rows,y_cols;
-	int nods;
+	int     nods;
 
 	/*Output*/
@@ -36,5 +36,5 @@
 
 	/*Input datasets: */
-	if (verbose) _printLine_("Fetching inputs");
+	if (verbose) _printf_("Fetching inputs\n");
 	FetchData(&x,&nods,&x_cols,XHANDLE);
 	FetchData(&y,&y_rows,&y_cols,YHANDLE);
@@ -46,5 +46,5 @@
 
 	/* Run core computations: */
-	if (verbose) _printLine_("Call core");
+	if (verbose) _printf_("Call core\n");
 	BamgTriangulatex(&index,&nels,x,y,nods);
 
@@ -52,4 +52,9 @@
 	WriteData(INDEX,index,nels,3);
 
+	/*Clean up*/
+	xDelete<int>(index);
+	xDelete<double>(x);
+	xDelete<double>(y);
+
 	/*end module: */
 	MODULEEND();
Index: /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.h
===================================================================
--- /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.h	(revision 15395)
+++ /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/Chaco/Chaco.cpp
===================================================================
--- /issm/trunk/src/wrappers/Chaco/Chaco.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/Chaco/Chaco.cpp	(revision 15396)
@@ -12,10 +12,10 @@
 
 void ChacoUsage(void){/*{{{*/
-	_pprintLine_("");
-	_pprintLine_("Usage: [assgn] = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);");
-	_pprintLine_("");
+	_printf0_("\n");
+	_printf0_("Usage: [assgn] = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(Chaco){
-   
+
 	int i;
 	int nterms;
@@ -83,31 +83,31 @@
 	nparts=xNew<int>(1); nparts[0]=npart; //weird Chacox interface ain't it?
 	FetchData(&goal,&nterms,GOAL_IN); 
-	
+
 	/*Some debugging print: {{{*/
 	#ifdef _DEBUG_
-	_printLine_("nvtxs: " << nvtxs);
-	_printString_("options: [");
-	for(i=0;i<10;i++)_printString_(options[i] << "|");
-	_printLine_("]");
-	_printLine_("start: ");
-	for (i=0; i<nvtxs+1;i++)_printString_(start[i] << " ");
-	_printLine_("");
-	_printLine_("adjacency: ");
-	for (i=0; i<mxGetNzmax(A_IN);i++)_printString_("" <<adjacency[i]<< " ");i++)
-	_printLine_("");
-	_printLine_("nedges: " << nedges << " " << ewgts);
-	if(ewgts) for (i = 0; i < nedges; i++)_printString_(ewgts[i] << " ");
-	_printLine_("");
-	_printLine_("vwgts:");
-	for (i = 0; i < nvtxs; i++)_printString_(vwgts[i] << " ");
-	_printLine_("");
-	_printLine_("nparts: " << nparts[0]);
-	_printLine_("goal: " << goal);
+	_printf_("nvtxs: " << nvtxs << "\n");
+	_printf_("options: [");
+	for(i=0;i<10;i++)_printf_(options[i] << "|");
+	_printf_("]\n");
+	_printf_("start: \n");
+	for (i=0; i<nvtxs+1;i++)_printf_(start[i] << " ");
+	_printf_("\n");
+	_printf_("adjacency: \n");
+	for (i=0; i<mxGetNzmax(A_IN);i++)_printf_("" <<adjacency[i]<< " ");i++)
+	_printf_("\n");
+	_printf_("nedges: " << nedges << " " << ewgts << "\n");
+	if(ewgts) for (i = 0; i < nedges; i++)_printf_(ewgts[i] << " ");
+	_printf_("\n");
+	_printf_("vwgts:\n");
+	for (i = 0; i < nvtxs; i++)_printf_(vwgts[i] << " ");
+	_printf_("\n");
+	_printf_("nparts: " << nparts[0] << "\n");
+	_printf_("goal: " << goal << "\n");
 	#endif
 	/*}}}*/
-	
+
 	/*Allocate output: */
 	assignment = xNewZeroInit<short>(nvtxs);
-	
+
     /*Call core: */
 	Chacox(nvtxs, start, adjacency, vwgts, ewgts, x, y, z, assignment, options, nparts, goal);
Index: /issm/trunk/src/wrappers/Chaco/Chaco.h
===================================================================
--- /issm/trunk/src/wrappers/Chaco/Chaco.h	(revision 15395)
+++ /issm/trunk/src/wrappers/Chaco/Chaco.h	(revision 15396)
@@ -18,12 +18,11 @@
 
 /*headers*/
+#include "../bindings.h" /*Should always come first to avoid python's warnings*/
 #include <stdio.h>
 #include <string.h>    /*  strcasecmp  */
 #include <time.h>      /*  clock,time,difftime  */
-#include "../../c/include/globals.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.cpp
===================================================================
--- /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.cpp	(revision 15396)
@@ -3,43 +3,42 @@
     are inside this contour. 
 */
-	
+
 #include "./ContourToMesh.h"
 
 void ContourToMeshUsage(void){/*{{{*/
-	_printLine_("CONTOURTOMESH - Flag the elements or nodes inside a contour");
-	_printLine_("");
-	_printLine_("      Usage: ");
-	_printLine_("         [in_nod,in_elem]=ContourToMesh(index,x,y,contourname,interptype,edgevalue)\n");
-	_printLine_("");
-	_printLine_("         index,x,y: mesh triangulation.");
-	_printLine_("         contourname: name of .exp file containing the contours.");
-	_printLine_("         interptype: string definining type of interpolation ('element', or 'node').");
-	_printLine_("         edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons.");
-	_printLine_("         in_nod: vector of flags (0 or 1), of size nods if interptype is set to 'node' or 'element and node', ");
-	_printLine_("            or of size 0 otherwise.");
-	_printLine_("         in_elem: vector of flags (0 or 1), of size nel if interptype is set to 'element' or 'element and node', ");
-	_printLine_("            or of size 0 otherwise.");
-	_printLine_("");
-	_printLine_("      Example: ");
-	_printLine_("         in_nod=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','node',1)");
-	_printLine_("         in_elements=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','element',0)");
-	_printLine_("         [in_nodes,in_elements]=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','element and node',0)");
-	_printLine_("");
+	_printf_("CONTOURTOMESH - Flag the elements or nodes inside a contour\n");
+	_printf_("\n");
+	_printf_("      Usage: \n");
+	_printf_("         [in_nod,in_elem]=ContourToMesh(index,x,y,contourname,interptype,edgevalue)\n");
+	_printf_("\n");
+	_printf_("         index,x,y: mesh triangulation.\n");
+	_printf_("         contourname: name of .exp file containing the contours.\n");
+	_printf_("         interptype: string definining type of interpolation ('element', or 'node').\n");
+	_printf_("         edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons.\n");
+	_printf_("         in_nod: vector of flags (0 or 1), of size nods if interptype is set to 'node' or 'element and node', \n");
+	_printf_("            or of size 0 otherwise.\n");
+	_printf_("         in_elem: vector of flags (0 or 1), of size nel if interptype is set to 'element' or 'element and node', \n");
+	_printf_("            or of size 0 otherwise.\n");
+	_printf_("\n");
+	_printf_("      Example: \n");
+	_printf_("         in_nod=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','node',1)\n");
+	_printf_("         in_elements=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','element',0)\n");
+	_printf_("         [in_nodes,in_elements]=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','element and node',0)\n");
+	_printf_("\n");
 }/*}}}*/
 WRAPPER(ContourToMesh){
 
 	/* required input: */
-	int      edgevalue;
-	double  *index       = NULL;
-	int      nel;
-	double  *x           = NULL;
-	int      nods;
-	double  *y           = NULL;
-	char    *interptype  = NULL;
-	DataSet *contours    = NULL;
+	int       edgevalue;
+	int       nel,nods;
+	double   *index       = NULL;
+	double   *x           = NULL;
+	double   *y           = NULL;
+	char     *interptype  = NULL;
+	Contours *contours    = NULL;
 
 	/* output: */
-	SeqVec<double> *in_nod  = NULL;
-	SeqVec<double> *in_elem = NULL;
+	double *in_nod  = NULL;
+	double *in_elem = NULL;
 
 	/*Boot module: */
@@ -72,17 +71,25 @@
 	/* output: */
 	if (strcmp(interptype,"node")==0){
-		WriteData(PLHS0,in_nod);
+		WriteData(PLHS0,in_nod,nods);
 		WriteData(PLHS1);
 	}
 	else if (strcmp(interptype,"element")==0){
-		WriteData(PLHS0,in_elem);
+		WriteData(PLHS0,in_elem,nel);
 		WriteData(PLHS1);
 	}
 	else if (strcmp(interptype,"element and node")==0){
-		WriteData(PLHS0,in_nod);
-		WriteData(PLHS1,in_elem);
+		WriteData(PLHS0,in_nod,nods);
+		WriteData(PLHS1,in_elem,nel);
 	}
 	else _error_("wrong interpolation type");
 
+	/*Clean up*/
+	xDelete<double>(index);
+	xDelete<double>(x);
+	xDelete<double>(y);
+	xDelete<char>(interptype);
+	delete contours;
+	delete in_nod;
+	delete in_elem;
 	/*end module: */
 	MODULEEND();
Index: /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.h
===================================================================
--- /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.h	(revision 15395)
+++ /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.h	(revision 15396)
@@ -18,13 +18,11 @@
 
 /*Header files: */
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/toolkits/toolkits.h"
-#include "../../c/include/include.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
-#include "../../c/io/io.h"
-#include "../../c/EnumDefinitions/EnumDefinitions.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
 
 #undef __FUNCT__
@@ -64,3 +62,2 @@
 
 #endif  /* _CONTOURTOMESH_H */
-
Index: /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.cpp
===================================================================
--- /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.cpp	(revision 15396)
@@ -2,28 +2,28 @@
     \brief: takes a  contour file, and figures out which nodes  (x,y list)
 */
-	
+
 #include "./ContourToNodes.h"
 
 void ContourToNodesUsage(void){/*{{{*/
-	_printLine_("   usage:");
-	_printLine_("   [flags]=ContourToNodes(x,y,contourname,edgevalue);\n");
-	_printLine_("   where:");
-	_printLine_("      x,y: list of nodes.");
-	_printLine_("      contourname: name of .exp file containing the contours, or resulting structure from call to expread.");
-	_printLine_("      edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons.");
-	_printLine_("      flags: vector of flags (0 or 1), of size nods.");
-	_printLine_("");
+	_printf_("   usage:\n");
+	_printf_("   [flags]=ContourToNodes(x,y,contourname,edgevalue);\n");
+	_printf_("   where:\n");
+	_printf_("      x,y: list of nodes.\n");
+	_printf_("      contourname: name of .exp file containing the contours, or resulting structure from call to expread.\n");
+	_printf_("      edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons.\n");
+	_printf_("      flags: vector of flags (0 or 1), of size nods.\n");
+	_printf_("\n");
 }/*}}}*/
 WRAPPER(ContourToNodes){
 
 	/* input: */
-	int      edgevalue,nods;
-	double  *x           = NULL;
-	double  *y           = NULL;
-	char    *contourname = NULL;
-	DataSet *contours    = NULL;
+	int       edgevalue,nods;
+	double   *x           = NULL;
+	double   *y           = NULL;
+	char     *contourname = NULL;
+	Contours *contours    = NULL;
 
 	/* output: */
-	SeqVec<double> *flags = NULL;
+	double *flags = NULL;
 
 	/*Boot module: */
@@ -32,5 +32,5 @@
 	/*checks on arguments on the matlab side: */
 	CHECKARGUMENTS(NLHS,NRHS,&ContourToNodesUsage);
-	
+
 	/*Fetch inputs: */
 	FetchData(&x,&nods,NULL,XHANDLE);
@@ -43,5 +43,11 @@
 
 	/* output: */
-	WriteData(FLAGS,flags);
+	WriteData(FLAGS,flags,nods);
+
+	/*Clean up*/
+	xDelete<double>(x);
+	xDelete<double>(y);
+	xDelete<char>(contourname);
+	delete contours;
 
 	/*end module: */
Index: /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.h
===================================================================
--- /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.h	(revision 15395)
+++ /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__
@@ -55,3 +54,2 @@
 
 #endif  /* _CONTOURTONODES_H */
-
Index: /issm/trunk/src/wrappers/EdgeDetection/EdgeDetection.cpp
===================================================================
--- /issm/trunk/src/wrappers/EdgeDetection/EdgeDetection.cpp	(revision 15396)
+++ /issm/trunk/src/wrappers/EdgeDetection/EdgeDetection.cpp	(revision 15396)
@@ -0,0 +1,53 @@
+/*!\file EdgeDetection.c
+ * \brief: edge detection for a boolean image
+*/
+
+#include "./EdgeDetection.h"
+
+void EdgeDetectionUsage(void){/*{{{*/
+	_printf0_("EDGEDETECTION usage- detect edges of a boolean image\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      contours=EdgeDetection(image);\n");
+	_printf0_("\n");
+	_printf0_("      image: boolean matrix\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      load('velocities.mat');\n");
+	_printf0_("      md.inversion.vx_obs=EdgeDetection(x_n,y_m,vx,md.mesh.x,md.mesh.y,0);\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(EdgeDetection){
+
+	/*input: */
+	bool *image = NULL;
+	int   M,N;
+
+	/* output: */
+	Contours* contours=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&EdgeDetectionUsage);
+
+	/*Input datasets: */
+	FetchData(&image,&M,&N,IMAGE);
+
+	/*Initialize output: */
+	contours=new Contours();
+
+	/* Run core computations: */
+	EdgeDetectionx(contours,image,M,N);
+
+	/*Write data: */
+	WriteData(CONTOURS,contours);
+
+	/*Clean up*/
+	xDelete<bool>(image);
+	delete contours;
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/EdgeDetection/EdgeDetection.h
===================================================================
--- /issm/trunk/src/wrappers/EdgeDetection/EdgeDetection.h	(revision 15396)
+++ /issm/trunk/src/wrappers/EdgeDetection/EdgeDetection.h	(revision 15396)
@@ -0,0 +1,51 @@
+/*!\file EdgeDetection.h
+ * \brief: prototype for EdgeDetection module 
+ */
+
+#ifndef _EDGEDETECTION_H_
+#define _EDGEDETECTION_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
+#include "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "EdgeDetection"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define IMAGE       prhs[0]
+/* serial output macros: */
+#define CONTOURS (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define IMAGE       PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define CONTOURS output,0
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  1
+
+#endif  /* _EDGEDETECTION_H_ */
Index: /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.cpp
===================================================================
--- /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.cpp	(revision 15396)
@@ -6,7 +6,7 @@
 
 void ElementConnectivityUsage(void) {/*{{{*/
-	_pprintLine_("");
-	_pprintLine_("   usage: elementconnectivity = " << __FUNCT__ << "(elements, nodeconnectivity);");
-	_pprintLine_("");
+	_printf0_("\n");
+	_printf0_("   usage: elementconnectivity = " << __FUNCT__ << "(elements, nodeconnectivity);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(ElementConnectivity){
@@ -26,5 +26,5 @@
 	/*checks on arguments: */
 	CHECKARGUMENTS(NLHS,NRHS,&ElementConnectivityUsage);
-        
+
 	/*Input datasets: */
 	FetchData(&elements,&nels,NULL,ELEMENTS);
@@ -37,4 +37,8 @@
 	WriteData(ELEMENTCONNECTIVITY,elementconnectivity,nels,3);
 
+	/*Clean up*/
+	xDelete<int>(nodeconnectivity);
+	xDelete<int>(elementconnectivity);
+
 	/*end module: */
 	MODULEEND();
Index: /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.h
===================================================================
--- /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.h	(revision 15395)
+++ /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.h	(revision 15396)
@@ -18,13 +18,11 @@
 
 /*Header files: */
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/toolkits/toolkits.h"
-#include "../../c/include/include.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
-#include "../../c/io/io.h"
-#include "../../c/EnumDefinitions/EnumDefinitions.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/EnumToString/EnumToString.cpp
===================================================================
--- /issm/trunk/src/wrappers/EnumToString/EnumToString.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/EnumToString/EnumToString.cpp	(revision 15396)
@@ -6,7 +6,7 @@
 
 void EnumToStringUsage(void){/*{{{*/
-	_pprintLine_("");
-	_pprintLine_("   usage: " << __FUNCT__ << "string = EnumToString(enum);");
-	_pprintLine_("");
+	_printf0_("\n");
+	_printf0_("   usage: " << __FUNCT__ << "string = EnumToString(enum);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(EnumToString){
@@ -30,4 +30,7 @@
 	WriteData(NAME,name);
 
+	/*Clean up*/
+	xDelete<char>(name);
+
 	/*end module: */
 	MODULEEND();
Index: /issm/trunk/src/wrappers/EnumToString/EnumToString.h
===================================================================
--- /issm/trunk/src/wrappers/EnumToString/EnumToString.h	(revision 15395)
+++ /issm/trunk/src/wrappers/EnumToString/EnumToString.h	(revision 15396)
@@ -18,13 +18,12 @@
 
 /*Header files: */
-#include "../../c/include/globals.h"
-#include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/shared/Enum/Enum.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
 #define __FUNCT__  "EnumToString"
- 
+
 #ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
Index: /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.cpp
===================================================================
--- /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.cpp	(revision 15396)
@@ -5,26 +5,26 @@
 
 void Exp2KmlUsage(void){/*{{{*/
-	_pprintLine_("Exp2Kml - exp to kml file conversion module:");
-	_pprintLine_("");
-	_pprintLine_("   This module converts a file from exp to kml format.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [ret]=Exp2Kml(filexp,filkml,sgn,'param name',param,...);");
-	_pprintLine_("");
-	_pprintLine_("      filexp      file name of exp file to be read (char)");
-	_pprintLine_("      filkml      file name of kml file to be written (char)");
-	_pprintLine_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))");
-	_pprintLine_("");
-	_pprintLine_("      central_meridian     central meridian (double, optional, but must specify with sp)");
-	_pprintLine_("      standard_parallel    standard parallel (double, optional, but must specify with cm)");
-	_pprintLine_("      holes       flag for treatment of multiple profiles (char, optional, 'yes' for holes))");
-	_pprintLine_("");
-	_pprintLine_("      ret         return code (non-zero for warning)");
-	_pprintLine_("");
-	_pprintLine_("   Examples:");
-	_pprintLine_("      [ret]=Exp2Kml('file.exp','file.kml', 1);");
-	_pprintLine_("      [ret]=Exp2Kml('file.exp','file.kml', 1,'central_meridian',45,'standard_parallel',70,'holes','yes');");
-	_pprintLine_("      [ret]=Exp2Kml('file.exp','file.kml',-1,'central_meridian', 0,'standard_parallel',71,'holes','yes');");
-	_pprintLine_("");
+	_printf0_("Exp2Kml - exp to kml file conversion module:\n");
+	_printf0_("\n");
+	_printf0_("   This module converts a file from exp to kml format.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [ret]=Exp2Kml(filexp,filkml,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      filexp      file name of exp file to be read (char)\n");
+	_printf0_("      filkml      file name of kml file to be written (char)\n");
+	_printf0_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf0_("\n");
+	_printf0_("      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf0_("      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf0_("      holes       flag for treatment of multiple profiles (char, optional, 'yes' for holes))\n");
+	_printf0_("\n");
+	_printf0_("      ret         return code (non-zero for warning)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [ret]=Exp2Kml('file.exp','file.kml', 1);\n");
+	_printf0_("      [ret]=Exp2Kml('file.exp','file.kml', 1,'central_meridian',45,'standard_parallel',70,'holes','yes');\n");
+	_printf0_("      [ret]=Exp2Kml('file.exp','file.kml',-1,'central_meridian', 0,'standard_parallel',71,'holes','yes');\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(Exp2Kml){
@@ -67,7 +67,7 @@
 	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
 		options->Get(&cm,"central_meridian");
-		if (verbose) _printLine_("  cm=" << cm);
+		if (verbose) _printf_("  cm=" << cm << "\n");
 		options->Get(&sp,"standard_parallel");
-		if (verbose) _printLine_("  sp=" << sp);
+		if (verbose) _printf_("  sp=" << sp << "\n");
 	}
 
Index: /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.h
===================================================================
--- /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.h	(revision 15395)
+++ /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/ExpSimplify/ExpSimplify.cpp
===================================================================
--- /issm/trunk/src/wrappers/ExpSimplify/ExpSimplify.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/ExpSimplify/ExpSimplify.cpp	(revision 15396)
@@ -5,15 +5,18 @@
 
 void ExpSimplifyUsage(void){/*{{{*/
-	_pprintLine_("ExpSimplify - Simplify Exp contour");
-	_pprintLine_("");
-	_pprintLine_("   Recursive Douglas-Peucker Polygon Simplification");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      ExpSimplify(expfile,tol);");
-	_pprintLine_("      - expfile: name of the exp file");
-	_pprintLine_("      - tol:  tolerance (maximal euclidean distance allowed between the new line and a vertex)");
-	_pprintLine_("");
-	_pprintLine_("   Example:");
-	_pprintLine_("      ExpSimplify('file.exp',100);");
+	_printf_("ExpSimplify - Simplify Exp contour\n");
+	_printf_("\n");
+	_printf_("   Recursive Douglas-Peucker Polygon Simplification\n");
+	_printf_("\n");
+	_printf_("   Usage:\n");
+	_printf_("      ExpSimplify(expfile,tol);\n");
+	_printf_("      - expfile: name of the exp file\n");
+	_printf_("      - tol:  tolerance (maximal euclidean distance allowed between the new line and a vertex)\n");
+	_printf_("      Additional options:\n");
+	_printf_("      - 'min': minimum number of vertices to save contours in exp file (default is 3)\n");
+	_printf_("\n");
+	_printf_("   Example:\n");
+	_printf_("      ExpSimplify('file.exp',100);\n");
+	_printf_("      ExpSimplify('file.exp',100,'remove1',false);\n");
 }/*}}}*/
 void simplify(Contour<double>* contour,bool* flags,int ind0,int ind1,double tolerance){/*{{{*/
@@ -22,5 +25,5 @@
 	double  distance,beta,dx,dy;
 	double  maxdistance;
-	int     index;
+	int     index  = -1;
 	double *x      = contour->x;
 	double *y      = contour->y;
@@ -37,9 +40,9 @@
 
 		/*calculate the shortest distance of all vertices between ind0 and ind1*/
-		for(int i=ind0;i<ind1;i++){
-			distance = sqrt((x[i]-x[i+1])*(x[i]-x[i+1]) + (y[i]-y[i+1])*(y[i]-y[i+1]));
+		for(int i=ind0;i<ind1-1;i++){
+			distance = sqrt((x[ind0]-x[i+1])*(x[ind0]-x[i+1]) + (y[ind0]-y[i+1])*(y[ind0]-y[i+1]));
 			if(i==ind0 || distance>maxdistance){
 				maxdistance=distance;
-				index = i;
+				index = i + 1;
 			}
 		}
@@ -54,6 +57,6 @@
 		 *
 		 * So: beta = <x-x0,xend-x0>/<xend-x0,xend-x0>  */
-		 
-		for(int i=ind0+1;i<ind1;i++){
+
+		for(int i=ind0+1;i<=ind1;i++){
 			beta = ((x[i]-x[ind0])*(x[ind1]-x[ind0]) + (y[i]-y[ind0])*(y[ind1]-y[ind0]))/((x[ind1]-x[ind0])*(x[ind1]-x[ind0])+(y[ind1]-y[ind0])*(y[ind1]-y[ind0]));
 			dx   = x[i]-beta*x[ind1]+(beta-1.)*x[ind0];
@@ -77,8 +80,10 @@
 		/*if not, call simplifyrec for the segments between ind0 and index
 		 * (index and ind1)*/
+		_assert_(index!=-1);
+		_assert_(index!=ind1);
+		_assert_(index!=ind0);
 		simplify(contour,flags,ind0 ,index,tolerance);
 		simplify(contour,flags,index,ind1, tolerance);
 	}
-
 
 }/*}}}*/
@@ -90,8 +95,11 @@
 	char*    expfile  = NULL;
 	double   tolerance;
+	Options *options      = NULL;
+	double   minimumvertices_double;
+	int      minimumvertices;
 
 	/*output*/
-	DataSet* oldcontours = NULL;
-	DataSet* newcontours = NULL;
+	Contours* oldcontours = NULL;
+	Contours* newcontours = NULL;
 
 	/*Boot module: */
@@ -99,9 +107,13 @@
 
 	/*checks on arguments: */
-	CHECKARGUMENTS(NLHS,NRHS,&ExpSimplifyUsage);
+	/*checks on arguments on the matlab side: */
+	if (nrhs<NRHS || nlhs>NLHS){
+		ExpSimplifyUsage(); _error_("ExpSimplify usage error");
+	}
 
 	/*Input datasets: */
 	FetchData(&expfile,  EXPFILE);
 	FetchData(&tolerance,TOLERANCE);
+	FetchData(&options,NRHS,nrhs,prhs);
 
 	/*some checks*/
@@ -117,7 +129,12 @@
 	double distance;
 
+	/*Process options*/
+	options->Get(&minimumvertices_double,"min",3.);
+	if(minimumvertices_double<1.) _error_("'min' (minimum number of verties) should be a positive integer");
+	minimumvertices = int(minimumvertices_double);
+
 	/*Read old contours and allocate new contours*/
-	oldcontours=DomainOutlineRead<double>(expfile);
-	newcontours=new DataSet(0);
+	oldcontours=ExpRead<double>(expfile);
+	newcontours=new Contours();
 	for(int counter=0;counter<oldcontours->Size();counter++){
 
@@ -127,5 +144,5 @@
 		x       = contour->x;
 		y       = contour->y;
-		printf("   Initial number of vertices in contour #%i: %i\n",counter+1,nods);
+		_printf_("   Initial number of vertices in contour #"<<counter+1<<": "<<nods << "\n");
 
 		/*Allocate flags (1=keep, 0=remove)*/
@@ -162,7 +179,9 @@
 		newnods = 0;
 		for(int i=0;i<nods;i++) if(flags[i]) newnods++;
-		printf("   New     number of vertices in contour #%i: %i\n",counter+1,newnods);
-		if(newnods){
-			newcontour       = xNew<Contour<double> >(1);
+
+		/*Do we save new profile?*/
+		if(newnods>=minimumvertices){
+			_printf_("   Final   number of vertices in contour #"<<counter+1<<": "<<newnods << "\n");
+			newcontour       = new Contour<double>();
 			newcontour->nods = newnods;
 			newcontour->x    = xNew<double>(newnods);
@@ -181,8 +200,13 @@
 			newcontours->AddObject(newcontour);
 		}
+		else{
+			_printf_("   Final   number of vertices in contour #"<<counter+1<<": "<<newnods<<" (not saved)\n");
+		}
 
 		/*cleanup*/
 		xDelete<bool>(flags);
 	}
+	_printf_("   Initial number of contours: "<<oldcontours->Size() << "\n");
+	_printf_("   Final   number of contours: "<<newcontours->Size() << "\n");
 
 	/*Write data: */
@@ -191,4 +215,5 @@
 	/*Clean-up*/
 	xDelete<char>(expfile);
+	delete options;
 
 	/*end module: */
Index: /issm/trunk/src/wrappers/ExpSimplify/ExpSimplify.h
===================================================================
--- /issm/trunk/src/wrappers/ExpSimplify/ExpSimplify.h	(revision 15395)
+++ /issm/trunk/src/wrappers/ExpSimplify/ExpSimplify.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/HoleFiller/HoleFiller.cpp
===================================================================
--- /issm/trunk/src/wrappers/HoleFiller/HoleFiller.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/HoleFiller/HoleFiller.cpp	(revision 15396)
@@ -13,15 +13,13 @@
 
 void HoleFillerUsage(void){/*{{{*/
-	_printLine_("   HoleFiller usage:");
-	_printLine_("   [image_out]=HoleFiller(image_in,smooth);\n");
-	_printLine_("   where:");
-	_printLine_("      image_in in double format");
-	_printLine_("      smooth: 1 to smooth with a box filer, 0 to leave data raw");
-	_printLine_("      image_out in double format");
-	_printLine_("");
+	_printf_("   HoleFiller usage:\n");
+	_printf_("   [image_out]=HoleFiller(image_in,smooth);\n");
+	_printf_("   where:\n");
+	_printf_("      image_in in double format\n");
+	_printf_("      smooth: 1 to smooth with a box filer, 0 to leave data raw\n");
+	_printf_("      image_out in double format\n");
+	_printf_("\n");
 }/*}}}*/
 WRAPPER(HoleFiller){
-
-	int i,j;
 
 	/* required input: */
@@ -31,7 +29,5 @@
 	int     smooth;
 
-
 	/* output: */
-	mxArray* pfield=NULL;
 	double* imageout=NULL;
 	int     imageout_rows,imageout_cols;
@@ -46,5 +42,5 @@
 	FetchData(&imagein,&imagein_rows,&imagein_cols,IMAGEIN);
 	FetchData(&smooth_flag,SMOOTH);
-	
+
 	/*Get smooth flag setup: */
 	if (smooth_flag==0)
@@ -59,4 +55,9 @@
 	WriteData(IMAGEOUT,imageout,imagein_rows,imagein_cols);
 
+	/*Clean up*/
+	xDelete<double>(imagein);
+	xDelete<double>(imageout);
+	xDelete<double>(imagein);
+
 	/*end module: */
 	MODULEEND();
Index: /issm/trunk/src/wrappers/HoleFiller/HoleFiller.h
===================================================================
--- /issm/trunk/src/wrappers/HoleFiller/HoleFiller.h	(revision 15395)
+++ /issm/trunk/src/wrappers/HoleFiller/HoleFiller.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/InternalFront/InternalFront.cpp
===================================================================
--- /issm/trunk/src/wrappers/InternalFront/InternalFront.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/InternalFront/InternalFront.cpp	(revision 15396)
@@ -6,7 +6,7 @@
 
 void InternalFrontUsage(void) {/*{{{*/
-	_pprintLine_("");
-	_pprintLine_("   usage: icefront = " << __FUNCT__ << "(md);");
-	_pprintLine_("");
+	_printf0_("\n");
+	_printf0_("   usage: icefront = " << __FUNCT__ << "(md);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(InternalFront){
Index: /issm/trunk/src/wrappers/InternalFront/InternalFront.h
===================================================================
--- /issm/trunk/src/wrappers/InternalFront/InternalFront.h	(revision 15395)
+++ /issm/trunk/src/wrappers/InternalFront/InternalFront.h	(revision 15396)
@@ -17,8 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
-#include "../../c/io/io.h"
+#include "../../c/shared/io/io.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 15396)
@@ -2,26 +2,26 @@
  * \brief: data interpolation from a list of (x,y,values) into mesh vertices
 */
-	
+
 #include "./InterpFromGridToMesh.h"
 
 void InterpFromGridToMeshUsage(void){/*{{{*/
-	_pprintLine_("INTERPFROMGRIDTOMESH - interpolation from a grid onto a list of points");
-	_pprintLine_("");
-	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
-	_pprintLine_("   defined on a grid onto a list of points");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      data_mesh=InterpFromGridToMesh(x,y,data,x_mesh,y_mesh,default_value);");
-	_pprintLine_("");
-	_pprintLine_("      data: matrix holding the data to be interpolated onto the mesh.");
-	_pprintLine_("      x,y: coordinates of matrix data. (x and y must be in increasing order)");
-	_pprintLine_("      x_mesh,y_mesh: coordinates of the points onto which we interpolate.");
-	_pprintLine_("      default_value: default value if no data is found (holes).");
-	_pprintLine_("      data_mesh: vector of mesh interpolated data.");
-	_pprintLine_("");
-	_pprintLine_("   Example:");
-	_pprintLine_("      load('velocities.mat');");
-	_pprintLine_("      md.inversion.vx_obs=InterpFromGridToMesh(x_n,y_m,vx,md.mesh.x,md.mesh.y,0);");
-	_pprintLine_("");
+	_printf0_("INTERPFROMGRIDTOMESH - interpolation from a grid onto a list of points\n");
+	_printf0_("\n");
+	_printf0_("   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf0_("   defined on a grid onto a list of points\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      data_mesh=InterpFromGridToMesh(x,y,data,x_mesh,y_mesh,default_value);\n");
+	_printf0_("\n");
+	_printf0_("      data: matrix holding the data to be interpolated onto the mesh.\n");
+	_printf0_("      x,y: coordinates of matrix data. (x and y must be in increasing order)\n");
+	_printf0_("      x_mesh,y_mesh: coordinates of the points onto which we interpolate.\n");
+	_printf0_("      default_value: default value if no data is found (holes).\n");
+	_printf0_("      data_mesh: vector of mesh interpolated data.\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      load('velocities.mat');\n");
+	_printf0_("      md.inversion.vx_obs=InterpFromGridToMesh(x_n,y_m,vx,md.mesh.x,md.mesh.y,0);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(InterpFromGridToMesh){
@@ -42,5 +42,5 @@
 
 	/* output: */
-	SeqVec<double>*  data_mesh=NULL;
+	IssmSeqVec<double>*  data_mesh=NULL;
 
 	/*Boot module: */
Index: /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 15395)
+++ /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 15396)
@@ -2,21 +2,21 @@
  * \brief: data interpolation from a list of (x,y,values) into mesh vertices
 */
-	
+
 #include "./InterpFromMesh2d.h"
 
 void InterpFromMesh2dUsage(void){/*{{{*/
-	_pprintLine_("   usage:");
-	_pprintLine_("         data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime);\n");
-	_pprintLine_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value);\n");
-	_pprintLine_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value,contourname);\n");
-	_pprintLine_("   where:");
-	_pprintLine_("      x,y: coordinates of the nodes where data is defined");
-	_pprintLine_("      index: index of the mesh where data is defined");
-	_pprintLine_("      data - vector holding the data to be interpolated onto the points.");
-	_pprintLine_("      x_prime,y_prime: coordinates of the mesh vertices onto which we interpolate.");
-	_pprintLine_("      default_value: a scalar or vector of size length(x_prime).");
-	_pprintLine_("      contourname: linear interpolation will happen on all x_interp,y_interp inside the contour, default value will be adopted on the rest of the mesh.");
-	_pprintLine_("      data_prime:  vector of prime interpolated data.");
-	_pprintLine_("");
+	_printf0_("   usage:\n");
+	_printf0_("         data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime);\n");
+	_printf0_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value);\n");
+	_printf0_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value,contourname);\n");
+	_printf0_("   where:\n");
+	_printf0_("      x,y: coordinates of the nodes where data is defined\n");
+	_printf0_("      index: index of the mesh where data is defined\n");
+	_printf0_("      data - vector holding the data to be interpolated onto the points.\n");
+	_printf0_("      x_prime,y_prime: coordinates of the mesh vertices onto which we interpolate.\n");
+	_printf0_("      default_value: a scalar or vector of size length(x_prime).\n");
+	_printf0_("      contourname: linear interpolation will happen on all x_interp,y_interp inside the contour, default value will be adopted on the rest of the mesh.\n");
+	_printf0_("      data_prime:  vector of prime interpolated data.\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(InterpFromMesh2d){
@@ -29,5 +29,5 @@
 	double* x_data=NULL;
 	int     x_data_rows;
-	
+
 	double* y_data=NULL;
 	int     y_data_rows;
@@ -39,8 +39,7 @@
 	double* x_prime=NULL;
 	double* y_prime=NULL;
-	
+
 	int     x_prime_rows;
 	int     y_prime_rows;
-
 
 	double* default_values=NULL;
@@ -60,5 +59,5 @@
 
 	/* output: */
-	SeqVec<double> *data_prime = NULL;
+	IssmSeqVec<double> *data_prime = NULL;
 
 	/*Boot module: */
@@ -93,5 +92,5 @@
 
 	if(nrhs>=8){
-		
+
 		/*Call expread on filename to build a contour array in the matlab workspace: */
 		mexCallMATLAB( 1, &matlabstructure, 1, (mxArray**)&FILENAME, "expread");
@@ -102,5 +101,5 @@
 		for(i=0;i<numcontours;i++){
 			//allocate
-			contouri=xNew<Contour<double> >(1);
+			contouri=new Contour<double>();
 			//retrieve dimension of this contour.
 			contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
@@ -113,9 +112,9 @@
 		/* Debugging of contours :{{{1*/
 		/*for(i=0;i<numcontours;i++){
-		  _printLine_("\nContour echo: contour number  " << i+1 << " / " << numcontours);
+		  _printf_("\nContour echo: contour number  " << i+1 << " / " << numcontours << "\n");
 		  contouri=*(contours+i);
-		  _printLine_("   Number of vertices " << contouri->nods);
+		  _printf_("   Number of vertices " << contouri->nods << "\n");
 		  for (j=0;j<contouri->nods;j++){
-		  _printLine_("   " << *(contouri->x+j) << "f " << *(contouri->y+j) << "f");
+		  _printf_("   " << *(contouri->x+j) << "f " << *(contouri->y+j) << "f\n");
 		  }
 		  }*/
@@ -127,5 +126,4 @@
 	}
 
-
 	/*some checks*/
 	if (x_data_rows!=y_data_rows){
@@ -135,5 +133,5 @@
 		_error_("vectors x_prime and y_prime should have the same length!");
 	}
-	
+
 	/*get number of elements and number of nodes in the data*/
 	nels_data=index_data_rows;
Index: /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.h	(revision 15395)
+++ /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 15396)
@@ -6,17 +6,17 @@
 
 void InterpFromMeshToGridUsage(void){/*{{{*/
-	_pprintLine_("INTERPFROMMESHTOGRID - interpolation of a data defined on a mesh onto a grid");
-	_pprintLine_("");
-	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
-	_pprintLine_("   defined on a triangular mesh onto a regular grid");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [x_m,y_m,griddata]=InterpFromMeshToGrid(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value)");
-	_pprintLine_("");
-	_pprintLine_("      index,x,y: delaunay triangulation defining the mesh.");
-	_pprintLine_("      meshdata: vertex values of data to be interpolated.");
-	_pprintLine_("      xmin,ymax,posting,nlines,ncols: parameters that define the grid");
-	_pprintLine_("      default_value: value of points located out of the mesh.");
-	_pprintLine_("");
+	_printf0_("INTERPFROMMESHTOGRID - interpolation of a data defined on a mesh onto a grid\n");
+	_printf0_("\n");
+	_printf0_("   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf0_("   defined on a triangular mesh onto a regular grid\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [x_m,y_m,griddata]=InterpFromMeshToGrid(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value)\n");
+	_printf0_("\n");
+	_printf0_("      index,x,y: delaunay triangulation defining the mesh.\n");
+	_printf0_("      meshdata: vertex values of data to be interpolated.\n");
+	_printf0_("      xmin,ymax,posting,nlines,ncols: parameters that define the grid\n");
+	_printf0_("      default_value: value of points located out of the mesh.\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(InterpFromMeshToGrid){
@@ -41,5 +41,4 @@
 	double* x_m=NULL;
 	double* y_m=NULL;
-
 
 	/*Boot module: */
@@ -72,5 +71,5 @@
 	/*Free ressources: */
 	//let matlab do this.
-	
+
 	/*end module: */
 	MODULEEND();
Index: /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 15395)
+++ /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 15396)
@@ -5,26 +5,26 @@
 
 void InterpFromMeshToMesh2dUsage(void){/*{{{*/
-	_pprintLine_("INTERFROMMESHTOMESH2D - interpolation from a 2d triangular mesh onto a list of point");
-	_pprintLine_("");
-	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
-	_pprintLine_("   defined on a Delaunay triangulation onto a list of point");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("         data_interp=InterpFromMeshToMesh2d(index,x,y,data,x_interp,y_interp);");
-	_pprintLine_("      or data_interp=InterpFromMeshToMesh2d(index,x,y,data,x_interp,y_interp,OPTIONS);");
-	_pprintLine_("");
-	_pprintLine_("      index             : index of the mesh where data is defined");
-	_pprintLine_("      x,y               : coordinates of the nodes where data is defined");
-	_pprintLine_("      data              : matrix holding the data to be interpolated onto the mesh. (one column per field)");
-	_pprintLine_("      x_interp,y_interp : coordinates of the points onto which we interpolate.");
-	_pprintLine_("      data_interp       : vector of mesh interpolated data.");
-	_pprintLine_("      Available options :");
-	_pprintLine_("         - 'default' : default value if point is outsite of triangulation (instead of linear interolation)");
-	_pprintLine_("");
-	_pprintLine_("   Example:");
-	_pprintLine_("      load('temperature.mat');");
-	_pprintLine_("      md.initialization.temperature=InterpFromMeshToMesh2d(index,x,y,temperature,md.mesh.x,md.mesh.y);");
-	_pprintLine_("      md.initialization.temperature=InterpFromMeshToMesh2d(index,x,y,temperature,md.mesh.x,md.mesh.y,'default',253);");
-	_pprintLine_("");
+	_printf0_("INTERFROMMESHTOMESH2D - interpolation from a 2d triangular mesh onto a list of point\n");
+	_printf0_("\n");
+	_printf0_("   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf0_("   defined on a Delaunay triangulation onto a list of point\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("         data_interp=InterpFromMeshToMesh2d(index,x,y,data,x_interp,y_interp);\n");
+	_printf0_("      or data_interp=InterpFromMeshToMesh2d(index,x,y,data,x_interp,y_interp,OPTIONS);\n");
+	_printf0_("\n");
+	_printf0_("      index             : index of the mesh where data is defined\n");
+	_printf0_("      x,y               : coordinates of the nodes where data is defined\n");
+	_printf0_("      data              : matrix holding the data to be interpolated onto the mesh. (one column per field)\n");
+	_printf0_("      x_interp,y_interp : coordinates of the points onto which we interpolate.\n");
+	_printf0_("      data_interp       : vector of mesh interpolated data.\n");
+	_printf0_("      Available options :\n");
+	_printf0_("         - 'default' : default value if point is outsite of triangulation (instead of linear interolation)\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      load('temperature.mat');\n");
+	_printf0_("      md.initialization.temperature=InterpFromMeshToMesh2d(index,x,y,temperature,md.mesh.x,md.mesh.y);\n");
+	_printf0_("      md.initialization.temperature=InterpFromMeshToMesh2d(index,x,y,temperature,md.mesh.x,md.mesh.y,'default',253);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(InterpFromMeshToMesh2d){
Index: /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 15395)
+++ /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 15396)
@@ -18,13 +18,11 @@
 
 /*Header files: */
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/toolkits/toolkits.h"
-#include "../../c/include/include.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
-#include "../../c/io/io.h"
-#include "../../c/EnumDefinitions/EnumDefinitions.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 15396)
@@ -2,27 +2,27 @@
  * \brief: data interpolation from a list of (x,y,values) into mesh vertices
 */
-	
+
 #include "./InterpFromMeshToMesh3d.h"
 
 void InterpFromMeshToMesh3dUsage(void){/*{{{*/
-	_pprintLine_("INTERPFROMMESHTOMESH3D - interpolation from a 3d hexahedron mesh onto a list of point");
-	_pprintLine_("");
-	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
-	_pprintLine_("   defined on a triangular mesh onto a list of point");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      data_prime=InterpFromMeshToMesh3d(index,x,y,z,data,x_prime,y_prime,z_prime,default_value);");
-	_pprintLine_("");
-	_pprintLine_("      index: index of the mesh where data is defined");
-	_pprintLine_("      x,y,z: coordinates of the nodes where data is defined");
-	_pprintLine_("      data: matrix holding the data to be interpolated onto the mesh.");
-	_pprintLine_("      x_prime,y_prime,z_prime: coordinates of the points onto which we interpolate.");
-	_pprintLine_("      default_value: default value if no data is found (holes).");
-	_pprintLine_("      data_prime: vector of mesh interpolated data.");
-	_pprintLine_("");
-	_pprintLine_("   Example:");
-	_pprintLine_("      load('temperature.mat');");
-	_pprintLine_("      md.initialization.temperature=InterpFromMeshToMesh3d(index,x,y,z,temperature,md.mesh.x,md.mesh.y,md.mesh.z,253);");
-	_pprintLine_("");
+	_printf0_("INTERPFROMMESHTOMESH3D - interpolation from a 3d hexahedron mesh onto a list of point\n");
+	_printf0_("\n");
+	_printf0_("   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf0_("   defined on a triangular mesh onto a list of point\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      data_prime=InterpFromMeshToMesh3d(index,x,y,z,data,x_prime,y_prime,z_prime,default_value);\n");
+	_printf0_("\n");
+	_printf0_("      index: index of the mesh where data is defined\n");
+	_printf0_("      x,y,z: coordinates of the nodes where data is defined\n");
+	_printf0_("      data: matrix holding the data to be interpolated onto the mesh.\n");
+	_printf0_("      x_prime,y_prime,z_prime: coordinates of the points onto which we interpolate.\n");
+	_printf0_("      default_value: default value if no data is found (holes).\n");
+	_printf0_("      data_prime: vector of mesh interpolated data.\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      load('temperature.mat');\n");
+	_printf0_("      md.initialization.temperature=InterpFromMeshToMesh3d(index,x,y,z,temperature,md.mesh.x,md.mesh.y,md.mesh.z,253);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(InterpFromMeshToMesh3d){
@@ -47,5 +47,5 @@
 	double* y_prime=NULL;
 	double* z_prime=NULL;
-	
+
 	int     x_prime_rows;
 	int     y_prime_rows;
@@ -60,5 +60,5 @@
 
 	/* output: */
-	SeqVec<double>*  data_prime=NULL;
+	IssmSeqVec<double>*  data_prime=NULL;
 
 	/*Boot module: */
Index: /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h	(revision 15395)
+++ /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.cpp
===================================================================
--- /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.cpp	(revision 15396)
@@ -5,23 +5,23 @@
 
 void KMLFileReadUsage(void){/*{{{*/
-	_pprintLine_("KMLFileRead - KML file reader module:");
-	_pprintLine_("");
-	_pprintLine_("   This module reads a KML file.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [ierror]=KMLFileRead(kmlfile,'param name',param,...);");
-	_pprintLine_("");
-	_pprintLine_("      kmlfile      file name of kml file to be read (char)");
-	_pprintLine_("");
-	_pprintLine_("      echo         echo command (char, optional, 'off'/'on')");
-	_pprintLine_("      deepecho     deep echo command (char, optional, 'off'/'on')");
-	_pprintLine_("      write        write command (char, optional, 'off'/'stdout'/kmlfile)");
-	_pprintLine_("");
-	_pprintLine_("      ierror       return code (non-zero for error)");
-	_pprintLine_("");
-	_pprintLine_("   Examples:");
-	_pprintLine_("      [ierror]=KMLFileRead('file.kml','deepecho','on');");
-	_pprintLine_("      [ierror]=KMLFileRead('filin.kml','echo','on','write','filout.kml');");
-	_pprintLine_("");
+	_printf0_("KMLFileRead - KML file reader module:\n");
+	_printf0_("\n");
+	_printf0_("   This module reads a KML file.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [ierror]=KMLFileRead(kmlfile,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      kmlfile      file name of kml file to be read (char)\n");
+	_printf0_("\n");
+	_printf0_("      echo         echo command (char, optional, 'off'/'on')\n");
+	_printf0_("      deepecho     deep echo command (char, optional, 'off'/'on')\n");
+	_printf0_("      write        write command (char, optional, 'off'/'stdout'/kmlfile)\n");
+	_printf0_("\n");
+	_printf0_("      ierror       return code (non-zero for error)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [ierror]=KMLFileRead('file.kml','deepecho','on');\n");
+	_printf0_("      [ierror]=KMLFileRead('filin.kml','echo','on','write','filout.kml');\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(KMLFileRead){
@@ -84,12 +84,12 @@
 	if (!strlen(filnam)) strcpy(filnam,"stdout");
 
-	if (verbose) _printLine_("Opening file \"" << filnam << "\".");
+	if (verbose) _printf_("Opening file \"" << filnam << "\".\n");
 	fidi=fopen(filnam,"r");
 
 	/* Run core computations: */
-	if (verbose) _printLine_("Calling core:");
+	if (verbose) _printf_("Calling core:\n");
 	kobj=KMLFileReadx(fidi);
 
-	if (verbose) _printLine_("Closing file \"" << filnam << "\".");
+	if (verbose) _printf_("Closing file \"" << filnam << "\".\n");
 	fclose(fidi);
 
@@ -104,8 +104,8 @@
 			}
 			else {
-				if (verbose) _printLine_("Opening file \"" << write << "\".");
+				if (verbose) _printf_("Opening file \"" << write << "\".\n");
 				fido=fopen(write,"w");
 				kobj->Write(fido,"");
-				if (verbose) _printLine_("Closing file \"" << write << "\".");
+				if (verbose) _printf_("Closing file \"" << write << "\".\n");
 				ierror=fclose(fido);
 			}
Index: /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.h
===================================================================
--- /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.h	(revision 15395)
+++ /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.cpp
===================================================================
--- /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.cpp	(revision 15396)
@@ -5,27 +5,27 @@
 
 void KMLMeshWriteUsage(void){/*{{{*/
-	_pprintLine_("KMLMeshWrite - KML mesh writer module:");
-	_pprintLine_("");
-	_pprintLine_("   This module writes the mesh of a model as KML polygons into the specified KML file.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      ierror=KMLMeshWrite(name,notes,elem,nodecon,lat,long,part,data,cmap,kmlfile);");
-	_pprintLine_("");
-	_pprintLine_("      name       model name (string, may be empty)");
-	_pprintLine_("      notes      model notes (string or cell array of strings, may be empty)");
-	_pprintLine_("      elem       elements (double array)");
-	_pprintLine_("      nodecon    nodal connectivity array (double array, may be empty)");
-	_pprintLine_("      lat        nodal latititudes (double vector)");
-	_pprintLine_("      long       nodal longitudes (double vector)");
-	_pprintLine_("      part       nodal partitions (double vector, may be empty)");
-	_pprintLine_("      data       nodal or element data (double vector, may be empty)");
-	_pprintLine_("      cmap       color map (double nx3 array, may be empty)");
-	_pprintLine_("      kmlfile    KML file name (string)");
-	_pprintLine_("");
-	_pprintLine_("      ierror     error flag (double, non-zero for error)");
-	_pprintLine_("");
-	_pprintLine_("   Example:");
-	_pprintLine_("      KMLMeshWrite(md.name,md.notes,md.elements,md.nodeconnectivity,md.lat,md.long,md.part,md.fm_criterion,options.cmap,filekml);");
-	_pprintLine_("");
+	_printf0_("KMLMeshWrite - KML mesh writer module:\n");
+	_printf0_("\n");
+	_printf0_("   This module writes the mesh of a model as KML polygons into the specified KML file.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      ierror=KMLMeshWrite(name,notes,elem,nodecon,lat,long,part,data,cmap,kmlfile);\n");
+	_printf0_("\n");
+	_printf0_("      name       model name (string, may be empty)\n");
+	_printf0_("      notes      model notes (string or cell array of strings, may be empty)\n");
+	_printf0_("      elem       elements (double array)\n");
+	_printf0_("      nodecon    nodal connectivity array (double array, may be empty)\n");
+	_printf0_("      lat        nodal latititudes (double vector)\n");
+	_printf0_("      long       nodal longitudes (double vector)\n");
+	_printf0_("      part       nodal partitions (double vector, may be empty)\n");
+	_printf0_("      data       nodal or element data (double vector, may be empty)\n");
+	_printf0_("      cmap       color map (double nx3 array, may be empty)\n");
+	_printf0_("      kmlfile    KML file name (string)\n");
+	_printf0_("\n");
+	_printf0_("      ierror     error flag (double, non-zero for error)\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      KMLMeshWrite(md.name,md.notes,md.elements,md.nodeconnectivity,md.lat,md.long,md.part,md.fm_criterion,options.cmap,filekml);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(KMLMeshWrite){
Index: /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.h
===================================================================
--- /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.h	(revision 15395)
+++ /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.cpp
===================================================================
--- /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.cpp	(revision 15396)
@@ -5,23 +5,23 @@
 
 void KMLOverlayUsage(void){/*{{{*/
-	_pprintLine_("KMLOverlay - KML file overlay module:");
-	_pprintLine_("");
-	_pprintLine_("   This module reads a list of image files and writes a KML or KMZ overlay file.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      ierror=KMLOverlay(kmlfile,'param name',param,...);");
-	_pprintLine_("");
-	_pprintLine_("      kmlfile     KML or KMZ file name (string)");
-	_pprintLine_("");
-	_pprintLine_("      lataxis     latitude axis (double vector [south north], required)");
-	_pprintLine_("      longaxis    longitude axis (double vector [west east], required)");
-	_pprintLine_("      images      relative or http image file names (string or array of strings or cell array of strings, required)");
-	_pprintLine_("      zip         flag to zip the doc.kml and image files into kmzfile (double, non-zero for kmz)");
-	_pprintLine_("");
-	_pprintLine_("      ierror     error flag (double, non-zero for error)");
-	_pprintLine_("");
-	_pprintLine_("   Example:");
-	_pprintLine_("      KMLOverlay(kmlfile,'lataxis',[south north],'longaxis',[west east],'images',{'file1.png','http://issm/file2.png'},'zip',1);");
-	_pprintLine_("");
+	_printf0_("KMLOverlay - KML file overlay module:\n");
+	_printf0_("\n");
+	_printf0_("   This module reads a list of image files and writes a KML or KMZ overlay file.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      ierror=KMLOverlay(kmlfile,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      kmlfile     KML or KMZ file name (string)\n");
+	_printf0_("\n");
+	_printf0_("      lataxis     latitude axis (double vector [south north], required)\n");
+	_printf0_("      longaxis    longitude axis (double vector [west east], required)\n");
+	_printf0_("      images      relative or http image file names (string or array of strings or cell array of strings, required)\n");
+	_printf0_("      zip         flag to zip the doc.kml and image files into kmzfile (double, non-zero for kmz)\n");
+	_printf0_("\n");
+	_printf0_("      ierror     error flag (double, non-zero for error)\n");
+	_printf0_("\n");
+	_printf0_("   Example:\n");
+	_printf0_("      KMLOverlay(kmlfile,'lataxis',[south north],'longaxis',[west east],'images',{'file1.png','http://issm/file2.png'},'zip',1);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(KMLOverlay){
@@ -63,11 +63,11 @@
 
 	options->Get(&lataxis ,&nlat ,(char*)"lataxis");
-	if (verbose && lataxis) for (i=0; i<nlat; i++) _printLine_("  lataxis [" << i << "]=" << lataxis[i]);
+	if (verbose && lataxis) for (i=0; i<nlat; i++) _printf_("  lataxis [" << i << "]=" << lataxis[i] << "\n");
 	options->Get(&longaxis,&nlong,(char*)"longaxis");
-	if (verbose && longaxis) for (i=0; i<nlong; i++) _printLine_("  longaxis[" << i << "]=" << longaxis[i]);
+	if (verbose && longaxis) for (i=0; i<nlong; i++) _printf_("  longaxis[" << i << "]=" << longaxis[i] << "\n");
 	options->Get(&pimages,&nimages,(char*)"images");
-	if (verbose && pimages) for (i=0; i<nimages; i++) _printLine_("  pimages[" << i << "]=\"" << pimages[i] << "\"");
+	if (verbose && pimages) for (i=0; i<nimages; i++) _printf_("  pimages[" << i << "]=\"" << pimages[i] << "\"\n");
 	options->Get(&dzip,(char*)"zip",0.);
-	if (verbose) _printLine_("  dzip=" << dzip);
+	if (verbose) _printf_("  dzip=" << dzip << "\n");
 
 	/*some checks*/
@@ -84,12 +84,12 @@
 	if(!strlen(filkml)) strcpy(filkml,"stdout");
 
-	if(verbose) _printLine_("Opening kml overlay file \"" << filkml << "\".");
+	if(verbose) _printf_("Opening kml overlay file \"" << filkml << "\".\n");
 	fid=fopen(filkml,"w");
 
 	/* Run core computations: */
-	if (verbose) _printLine_("Calling core:");
+	if (verbose) _printf_("Calling core:\n");
 	KMLOverlayx(&ierror,lataxis,longaxis,nimages,pimages,fid);
 
-	if (verbose) _printLine_("Closing file \"" << filkml << "\".");
+	if (verbose) _printf_("Closing file \"" << filkml << "\".\n");
 	fclose(fid);
 
@@ -108,6 +108,6 @@
 				strcat(czip,pimages[i]);
 			}
-		if (verbose) _printLine_("Zipping file \"" << filkmz << "\".");
-		if (verbose) _printLine_(czip);
+		if (verbose) _printf_("Zipping file \"" << filkmz << "\".\n");
+		if (verbose) _printf_(czip << "\n");
 
 		if (mexEvalString(czip)) _error_("Error zipping file \"" << filkmz << "\".");
Index: /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.h
===================================================================
--- /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.h	(revision 15395)
+++ /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.cpp
===================================================================
--- /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.cpp	(revision 15396)
@@ -5,25 +5,25 @@
 
 void Kml2ExpUsage(void){/*{{{*/
-	_pprintLine_("Kml2Exp - kml to exp file conversion module:");
-	_pprintLine_("");
-	_pprintLine_("   This module converts a file from kml to exp format.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [ret]=Kml2Exp(filexp,filkml,sgn,'param name',param,...);");
-	_pprintLine_("");
-	_pprintLine_("      filkml      file name of kml file to be read (char)");
-	_pprintLine_("      filexp      file name of exp file to be written (char)");
-	_pprintLine_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))");
-	_pprintLine_("");
-	_pprintLine_("      central_meridian     central meridian (double, optional, but must specify with sp)");
-	_pprintLine_("      standard_parallel    standard parallel (double, optional, but must specify with cm)");
-	_pprintLine_("");
-	_pprintLine_("      ret         return code (non-zero for warning)");
-	_pprintLine_("");
-	_pprintLine_("   Examples:");
-	_pprintLine_("      [ret]=Kml2Exp('file.kml','file.exp', 1);");
-	_pprintLine_("      [ret]=Kml2Exp('file.kml','file.exp', 1,'central_meridian',45,'standard_parallel',70);");
-	_pprintLine_("      [ret]=Kml2Exp('file.kml','file.exp',-1,'central_meridian', 0,'standard_parallel',71);");
-	_pprintLine_("");
+	_printf0_("Kml2Exp - kml to exp file conversion module:\n");
+	_printf0_("\n");
+	_printf0_("   This module converts a file from kml to exp format.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [ret]=Kml2Exp(filexp,filkml,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      filkml      file name of kml file to be read (char)\n");
+	_printf0_("      filexp      file name of exp file to be written (char)\n");
+	_printf0_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf0_("\n");
+	_printf0_("      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf0_("      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf0_("\n");
+	_printf0_("      ret         return code (non-zero for warning)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [ret]=Kml2Exp('file.kml','file.exp', 1);\n");
+	_printf0_("      [ret]=Kml2Exp('file.kml','file.exp', 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf0_("      [ret]=Kml2Exp('file.kml','file.exp',-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(Kml2Exp){
@@ -60,7 +60,7 @@
 	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
 		options->Get(&cm,"central_meridian");
-		if (verbose) _printLine_("  cm=" << cm);
+		if (verbose) _printf_("  cm=" << cm << "\n");
 		options->Get(&sp,"standard_parallel");
-		if (verbose) _printLine_("  sp=" << sp);
+		if (verbose) _printf_("  sp=" << sp << "\n");
 	}
 
Index: /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.h
===================================================================
--- /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.h	(revision 15395)
+++ /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/Kriging/Kriging.cpp
===================================================================
--- /issm/trunk/src/wrappers/Kriging/Kriging.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/Kriging/Kriging.cpp	(revision 15396)
@@ -9,22 +9,22 @@
 	num=_NUMTHREADS_;
 #endif
-	_pprintLine_("");
-	_pprintLine_("   usage: predictions=" << __FUNCT__ << "(x,y,observations,x_interp,y_interp,'options');");
-	_pprintLine_("   available options:");
-	_pprintLine_("      -'model': Available variogram models 'gaussian' (default),'spherical','power','exponential'");
-	_pprintLine_("         -'nugget': nugget effect (default 0.2)");
-	_pprintLine_("         -'range':  for gaussian, spherical and exponential models (default sqrt(3))");
-	_pprintLine_("         -'sill':   for gaussian, spherical and exponential models (default 1)");
-	_pprintLine_("         -'slope':  for power model (default 1)");
-	_pprintLine_("         -'power':  for power model (default 1)");
-	_pprintLine_("      -'searchradius': search radius for each prediction (default is observations span)");
-	_pprintLine_("      -'boxlength':    minimum length of quadtree boxes (useful to decrease the number of observations)");
-	_pprintLine_("      -'maxdata':      minimum number of observations for a prediction (default is 50)");
-	_pprintLine_("      -'mindata':      maximum number of observations for a prediction (default is 1)");
-	_pprintLine_("      -'maxtrimming':  maximum trimming value (default is -1.e+21)");
-	_pprintLine_("      -'mintrimming':  minimum trimming value (default is +1.e+21)");
-	_pprintLine_("      -'minspacing':   minimum distance between observation (default is 0.01)");
-	_pprintLine_("      -'numthreads':   number of threads, default is "<<num);
-	_pprintLine_("");
+	_printf0_("\n");
+	_printf0_("   usage: predictions=" << __FUNCT__ << "(x,y,observations,x_interp,y_interp,'options');\n");
+	_printf0_("   available options:\n");
+	_printf0_("      -'model': Available variogram models 'gaussian' (default),'spherical','power','exponential'\n");
+	_printf0_("         -'nugget': nugget effect (default 0.2)\n");
+	_printf0_("         -'range':  for gaussian, spherical and exponential models (default sqrt(3))\n");
+	_printf0_("         -'sill':   for gaussian, spherical and exponential models (default 1)\n");
+	_printf0_("         -'slope':  for power model (default 1)\n");
+	_printf0_("         -'power':  for power model (default 1)\n");
+	_printf0_("      -'searchradius': search radius for each prediction (default is observations span)\n");
+	_printf0_("      -'boxlength':    minimum length of quadtree boxes (useful to decrease the number of observations)\n");
+	_printf0_("      -'maxdata':      minimum number of observations for a prediction (default is 50)\n");
+	_printf0_("      -'mindata':      maximum number of observations for a prediction (default is 1)\n");
+	_printf0_("      -'maxtrimming':  maximum trimming value (default is -1.e+21)\n");
+	_printf0_("      -'mintrimming':  minimum trimming value (default is +1.e+21)\n");
+	_printf0_("      -'minspacing':   minimum distance between observation (default is 0.01)\n");
+	_printf0_("      -'numthreads':   number of threads, default is "<<num << "\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(Kriging){
Index: /issm/trunk/src/wrappers/Kriging/Kriging.h
===================================================================
--- /issm/trunk/src/wrappers/Kriging/Kriging.h	(revision 15395)
+++ /issm/trunk/src/wrappers/Kriging/Kriging.h	(revision 15396)
@@ -17,8 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/Ll2xy/Ll2xy.cpp
===================================================================
--- /issm/trunk/src/wrappers/Ll2xy/Ll2xy.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/Ll2xy/Ll2xy.cpp	(revision 15396)
@@ -5,26 +5,26 @@
 
 void Ll2xyUsage(void){/*{{{*/
-	_pprintLine_("Ll2xy - lat/long to x/y coordinate transformation module:");
-	_pprintLine_("");
-	_pprintLine_("   This module transforms lat/long to x/y coordinates.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [x,y]=Ll2xy(lat,lon,sgn,'param name',param,...);");
-	_pprintLine_("");
-	_pprintLine_("      lat         latitude coordinates (double vector)");
-	_pprintLine_("      lon         longitude coordinates (double vector)");
-	_pprintLine_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))");
-	_pprintLine_("");
-	_pprintLine_("      central_meridian     central meridian (double, optional, but must specify with sp)");
-	_pprintLine_("      standard_parallel    standard parallel (double, optional, but must specify with cm)");
-	_pprintLine_("");
-	_pprintLine_("      x           x coordinates (double vector)");
-	_pprintLine_("      y           y coordinates (double vector)");
-	_pprintLine_("");
-	_pprintLine_("   Examples:");
-	_pprintLine_("      [x,y]=Ll2xy(lat,lon, 1);");
-	_pprintLine_("      [x,y]=Ll2xy(lat,lon, 1,'central_meridian',45,'standard_parallel',70);");
-	_pprintLine_("      [x,y]=Ll2xy(lat,lon,-1,'central_meridian', 0,'standard_parallel',71);");
-	_pprintLine_("");
+	_printf0_("Ll2xy - lat/long to x/y coordinate transformation module:\n");
+	_printf0_("\n");
+	_printf0_("   This module transforms lat/long to x/y coordinates.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [x,y]=Ll2xy(lat,lon,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      lat         latitude coordinates (double vector)\n");
+	_printf0_("      lon         longitude coordinates (double vector)\n");
+	_printf0_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf0_("\n");
+	_printf0_("      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf0_("      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf0_("\n");
+	_printf0_("      x           x coordinates (double vector)\n");
+	_printf0_("      y           y coordinates (double vector)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [x,y]=Ll2xy(lat,lon, 1);\n");
+	_printf0_("      [x,y]=Ll2xy(lat,lon, 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf0_("      [x,y]=Ll2xy(lat,lon,-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(Ll2xy){
@@ -64,11 +64,11 @@
 	if(options->GetOption("central_meridian") || options->GetOption("standard_parallel")){
 		options->Get(&cm,"central_meridian");
-		if (verbose) _printLine_("  cm=" << cm);
+		if (verbose) _printf_("  cm=" << cm << "\n");
 		options->Get(&sp,"standard_parallel");
-		if (verbose) _printLine_("  sp=" << sp);
+		if (verbose) _printf_("  sp=" << sp << "\n");
 	}
 
 	/*some checks*/
-	if (verbose) _printLine_("Checking inputs:");
+	if (verbose) _printf_("Checking inputs:\n");
 	if (nlat != nlon){_error_("Must have same number of lat[" << nlat << "] and lon[" << nlon << "] coordinates.");}
 	else                ncoord=nlat;
Index: /issm/trunk/src/wrappers/Ll2xy/Ll2xy.h
===================================================================
--- /issm/trunk/src/wrappers/Ll2xy/Ll2xy.h	(revision 15395)
+++ /issm/trunk/src/wrappers/Ll2xy/Ll2xy.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp
===================================================================
--- /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 15396)
@@ -2,14 +2,14 @@
  * \brief: partition mesh according to number of areas, using Metis library.
 */
-	
+
 #include "./MeshPartition.h"
 
 void MeshPartitionUsage(void){/*{{{*/
-	_printLine_("   usage:");
-	_printString_("   [element_partitioning,node_partitioning]=MeshPartition(md.mesh,numpartitions)");
-	_printLine_("   where:");
-	_printLine_("      element_partitioning is a vector of partitioning area numbers, for every element.");
-	_printLine_("      node_partitioning is a vector of partitioning area numbers, for every node.");
-	_printLine_("");
+	_printf_("   usage:\n");
+	_printf_("   [element_partitioning,node_partitioning]=MeshPartition(md.mesh,numpartitions)");
+	_printf_("   where:\n");
+	_printf_("      element_partitioning is a vector of partitioning area numbers, for every element.\n");
+	_printf_("      node_partitioning is a vector of partitioning area numbers, for every node.\n");
+	_printf_("\n");
 }/*}}}*/
 WRAPPER(MeshPartition){
@@ -67,5 +67,5 @@
 		element_partitioning[i]=(double)int_element_partitioning[i]+1; //Metis indexing from 0, matlab from 1.
 	}
-	
+
 	node_partitioning=xNew<double>(numberofvertices);
 	for (i=0;i<numberofvertices;i++){
@@ -76,5 +76,5 @@
 	WriteData(ELEMENTPARTITIONING,element_partitioning,numberofelements);
 	WriteData(NODEPARTITIONING,node_partitioning,numberofvertices);
-	
+
 	/*Free ressources:*/
 	//don't! let matlab do it.
Index: /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h
===================================================================
--- /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h	(revision 15395)
+++ /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
@@ -50,5 +49,3 @@
 #define NRHS  2
 
-
 #endif  /* _MESHPARTITION_H */
-
Index: /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.cpp
===================================================================
--- /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 15396)
@@ -15,18 +15,18 @@
 		mesh.
 */
-	
+
 #include "./MeshProfileIntersection.h"
 
 void MeshProfileIntersectionUsage(void){/*{{{*/
-	_printLine_("   usage:");
-	_printLine_("   [segments]=MeshProfileIntersection(index,x,y,filename);");
-	_printLine_("   where:");
-	_printLine_("   input:");
-	_printLine_("        index,x,y is a triangulation");
-	_printLine_("        filename: name of Argus style .exp file containing the segments (can be groups of disconnected segments)");
-	_printLine_("   output:");
-	_printLine_("        segments: array made of x1,y1,x2,y2,element_id lines (x1,y1) and (x2,y2) are segment extremities for a segment ");
-	_printLine_("        belonging to the elemnt_id element. there are as many lines in segments as there are segments intersecting the ");
-	_printLine_("        mesh.");
+	_printf_("   usage:\n");
+	_printf_("   [segments]=MeshProfileIntersection(index,x,y,filename);\n");
+	_printf_("   where:\n");
+	_printf_("   input:\n");
+	_printf_("        index,x,y is a triangulation\n");
+	_printf_("        filename: name of Argus style .exp file containing the segments (can be groups of disconnected segments)\n");
+	_printf_("   output:\n");
+	_printf_("        segments: array made of x1,y1,x2,y2,element_id lines (x1,y1) and (x2,y2) are segment extremities for a segment \n");
+	_printf_("        belonging to the elemnt_id element. there are as many lines in segments as there are segments intersecting the \n");
+	_printf_("        mesh.\n");
 }/*}}}*/
 WRAPPER(MeshProfileIntersection){
@@ -36,14 +36,14 @@
 	/* required input: */
 	//mesh
-	double* double_index=NULL;
-	int*    index=NULL;
+	double *double_index = NULL;
+	int    *index        = NULL;
 	int     nel;
-	double* x=NULL;
-	double* y=NULL;
+	double *x            = NULL;
+	double *y            = NULL;
 	int     nods;
 	int     dummy;
-	
+
 	//contours
-	DataSet          *domain      = NULL;
+	Contours         *domain      = NULL;
 	Contour<double> **contours=NULL;
 	int               numcontours;
@@ -76,5 +76,5 @@
 	//contours
 	FetchData(&domain,FILENAME);
-	// MeshProfileIntersectionx should be modified to take DataSet directly (and perhaps SeqMat and SeqVec).
+	// MeshProfileIntersectionx should be modified to take DataSet directly (and perhaps IssmDenseMat and IssmSeqVec).
 	numcontours=domain->Size();
 	contours=xNew<Contour<double>*>(numcontours);
Index: /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.h
===================================================================
--- /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.h	(revision 15395)
+++ /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__
@@ -53,3 +52,2 @@
 
 #endif  /* _MESHPROFILEINTERSECTION_H */
-
Index: /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.cpp
===================================================================
--- /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.cpp	(revision 15396)
@@ -6,7 +6,7 @@
 
 void NodeConnectivityUsage(void){/*{{{*/
-	_pprintLine_("");
-	_pprintLine_("   usage: connectivity = " << __FUNCT__ << "(elements, numnodes);");
-	_pprintLine_("");
+	_printf0_("\n");
+	_printf0_("   usage: connectivity = " << __FUNCT__ << "(elements, numnodes);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(NodeConnectivity){
@@ -26,5 +26,5 @@
 	/*checks on arguments: */
 	CHECKARGUMENTS(NLHS,NRHS,&NodeConnectivityUsage);
-        
+
 	/*Input datasets: */
 	FetchData(&elements,&nels,NULL,ELEMENTS);
Index: /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.h
===================================================================
--- /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.h	(revision 15395)
+++ /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.h	(revision 15396)
@@ -21,13 +21,11 @@
 
 /*Header files: */
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/toolkits/toolkits.h"
-#include "../../c/include/include.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
-#include "../../c/io/io.h"
-#include "../../c/EnumDefinitions/EnumDefinitions.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
 
 #ifdef _HAVE_MATLAB_MODULES_
Index: /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp
===================================================================
--- /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 15396)
@@ -2,16 +2,16 @@
     \brief: flag points that are too near one another, within an array of point coordinates
 */
-	
+
 #include "./PointCloudFindNeighbors.h"
 
 void PointCloudFindNeighborsUsage(void){/*{{{*/
-	_printLine_("   usage:");
-	_printLine_("   [flags]=PointCloudFindNeighbors(x,y,mindistance,multithread);\n");
-	_printLine_("   where:");
-	_printLine_("      x,y: list of points.");
-	_printLine_("      mindistance: minimum distance that should exist between points in the cloud.");
-	_printLine_("      multithread: run multithreaded or not. with multithreads, flags can get 1 and 2 values in duplicates.");
-	_printLine_("      flags: array of flags (flag==1 means point is within mindistance of another point)");
-	_printLine_("");
+	_printf_("   usage:\n");
+	_printf_("   [flags]=PointCloudFindNeighbors(x,y,mindistance,multithread);\n");
+	_printf_("   where:\n");
+	_printf_("      x,y: list of points.\n");
+	_printf_("      mindistance: minimum distance that should exist between points in the cloud.\n");
+	_printf_("      multithread: run multithreaded or not. with multithreads, flags can get 1 and 2 values in duplicates.\n");
+	_printf_("      flags: array of flags (flag==1 means point is within mindistance of another point)\n");
+	_printf_("\n");
 }/*}}}*/
 WRAPPER(PointCloudFindNeighbors){
@@ -27,5 +27,5 @@
 
 	/* output: */
-	SeqVec<double> *flags = NULL;
+	IssmSeqVec<double> *flags = NULL;
 
 	/*Boot module: */
Index: /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.h
===================================================================
--- /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.h	(revision 15395)
+++ /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__
Index: /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp
===================================================================
--- /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 15396)
@@ -6,7 +6,7 @@
 
 void PropagateFlagsFromConnectivityUsage(void) {/*{{{*/
-	_printLine_("");
-	_printLine_("   usage: [pool] = " << __FUNCT__ << "(connectivity,pool,index,flags);");;
-	_printLine_("");
+	_printf_("\n");
+	_printf_("   usage: [pool] = " << __FUNCT__ << "(connectivity,pool,index,flags);\n");;
+	_printf_("\n");
 }/*}}}*/
 WRAPPER(PropagateFlagsFromConnectivity){
@@ -19,5 +19,5 @@
 	int     index;
 	int     dummy;
-	
+
 	/*Boot module: */
 	MODULEBOOT();
@@ -25,5 +25,5 @@
 	/*checks on arguments on the matlab side: */
 	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&PropagateFlagsFromConnectivityUsage);
-        
+
 	/*Input datasets: */
 	FetchData(&connectivity,&nel,&dummy,CONNECTIVITY);
Index: /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
===================================================================
--- /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h	(revision 15395)
+++ /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/Scotch/Scotch.cpp
===================================================================
--- /issm/trunk/src/wrappers/Scotch/Scotch.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/Scotch/Scotch.cpp	(revision 15396)
@@ -35,5 +35,5 @@
 
 	/* Check for proper number of arguments */
-   
+
 	if (nrhs == 0 && nlhs == 0) {
 		GmapUsage();
Index: /issm/trunk/src/wrappers/Scotch/Scotch.h
===================================================================
--- /issm/trunk/src/wrappers/Scotch/Scotch.h	(revision 15395)
+++ /issm/trunk/src/wrappers/Scotch/Scotch.h	(revision 15396)
@@ -6,13 +6,12 @@
 #define _SCOTCH_H
 
+#include "../bindings.h" /*Should always come first to avoid python's warnings*/
 #include <stdio.h>
 #include <string.h>    /*  strcasecmp  */
 #include <time.h>      /*  clock,time,difftime  */
-#include "../../c/include/globals.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
-    
+
 #undef __FUNCT__ 
 #define __FUNCT__  "Scotch"
Index: /issm/trunk/src/wrappers/Shp2Exp/Shp2Exp.cpp
===================================================================
--- /issm/trunk/src/wrappers/Shp2Exp/Shp2Exp.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/Shp2Exp/Shp2Exp.cpp	(revision 15396)
@@ -12,19 +12,19 @@
 
 void Shp2ExpUsage(void){/*{{{*/
-	_pprintLine_("Shp2Exp - shp to exp file conversion module:");
-	_pprintLine_("");
-	_pprintLine_("   This module converts a file from shp to exp format.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [ret]=Shp2Exp(filshp,filexp,sgn,'param name',param,...);");
-	_pprintLine_("");
-	_pprintLine_("      filshp      file name of shp file to be read (char, extension optional)");
-	_pprintLine_("      filexp      file name of exp file to be written (char)");
-	_pprintLine_("");
-	_pprintLine_("      ret         return code (non-zero for warning)");
-	_pprintLine_("");
-	_pprintLine_("   Examples:");
-	_pprintLine_("      [ret]=Shp2Exp('file.shp','file.exp');");
-	_pprintLine_("");
+	_printf0_("Shp2Exp - shp to exp file conversion module:\n");
+	_printf0_("\n");
+	_printf0_("   This module converts a file from shp to exp format.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [ret]=Shp2Exp(filshp,filexp,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      filshp      file name of shp file to be read (char, extension optional)\n");
+	_printf0_("      filexp      file name of exp file to be written (char)\n");
+	_printf0_("\n");
+	_printf0_("      ret         return code (non-zero for warning)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [ret]=Shp2Exp('file.shp','file.exp');\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(Shp2Exp){
Index: /issm/trunk/src/wrappers/Shp2Exp/Shp2Exp.h
===================================================================
--- /issm/trunk/src/wrappers/Shp2Exp/Shp2Exp.h	(revision 15395)
+++ /issm/trunk/src/wrappers/Shp2Exp/Shp2Exp.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
@@ -49,3 +48,2 @@
 
 #endif
-
Index: /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.cpp
===================================================================
--- /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.cpp	(revision 15396)
@@ -12,25 +12,25 @@
 
 void Shp2KmlUsage(void){/*{{{*/
-	_pprintLine_("Shp2Kml - shp to kml file conversion module:");
-	_pprintLine_("");
-	_pprintLine_("   This module converts a file from shp to kml format.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [ret]=Shp2Kml(filshp,filkml,sgn,'param name',param,...);");
-	_pprintLine_("");
-	_pprintLine_("      filshp      file name of shp file to be read (char, extension optional)");
-	_pprintLine_("      filkml      file name of kml file to be written (char)");
-	_pprintLine_("      sgn         sign for hemisphere (double, +1 (north); -1 (south); or 0 (no translation))");
-	_pprintLine_("");
-	_pprintLine_("      central_meridian     central meridian (double, optional, but must specify with sp)");
-	_pprintLine_("      standard_parallel    standard parallel (double, optional, but must specify with cm)");
-	_pprintLine_("");
-	_pprintLine_("      ret         return code (non-zero for warning)");
-	_pprintLine_("");
-	_pprintLine_("   Examples:");
-	_pprintLine_("      [ret]=Shp2Kml('file.shp','file.kml', 0);");
-	_pprintLine_("      [ret]=Shp2Kml('file.shp','file.kml', 1,'central_meridian',45,'standard_parallel',70);");
-	_pprintLine_("      [ret]=Shp2Kml('file.shp','file.kml',-1,'central_meridian', 0,'standard_parallel',71);");
-	_pprintLine_("");
+	_printf0_("Shp2Kml - shp to kml file conversion module:\n");
+	_printf0_("\n");
+	_printf0_("   This module converts a file from shp to kml format.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [ret]=Shp2Kml(filshp,filkml,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      filshp      file name of shp file to be read (char, extension optional)\n");
+	_printf0_("      filkml      file name of kml file to be written (char)\n");
+	_printf0_("      sgn         sign for hemisphere (double, +1 (north) -1 (south) or 0 (no translation))\n");
+	_printf0_("\n");
+	_printf0_("      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf0_("      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf0_("\n");
+	_printf0_("      ret         return code (non-zero for warning)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [ret]=Shp2Kml('file.shp','file.kml', 0);\n");
+	_printf0_("      [ret]=Shp2Kml('file.shp','file.kml', 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf0_("      [ret]=Shp2Kml('file.shp','file.kml',-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(Shp2Kml){
@@ -71,7 +71,7 @@
 	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
 		options->Get(&cm,"central_meridian");
-		if (verbose) _printLine_("  cm=" << cm);
+		if (verbose) _printf_("  cm=" << cm << "\n");
 		options->Get(&sp,"standard_parallel");
-		if (verbose) _printLine_("  sp=" << sp);
+		if (verbose) _printf_("  sp=" << sp << "\n");
 	}
 
Index: /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.h
===================================================================
--- /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.h	(revision 15395)
+++ /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
@@ -51,3 +50,2 @@
 
 #endif
-
Index: /issm/trunk/src/wrappers/StringToEnum/StringToEnum.cpp
===================================================================
--- /issm/trunk/src/wrappers/StringToEnum/StringToEnum.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/StringToEnum/StringToEnum.cpp	(revision 15396)
@@ -6,7 +6,7 @@
 
 void StringToEnumUsage(void){/*{{{*/
-	_pprintLine_("");
-	_pprintLine_("   usage: " << __FUNCT__ << "enum = StringToEnum(string);");
-	_pprintLine_("");
+	_printf0_("\n");
+	_printf0_("   usage: " << __FUNCT__ << "enum = StringToEnum(string);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(StringToEnum){
Index: /issm/trunk/src/wrappers/StringToEnum/StringToEnum.h
===================================================================
--- /issm/trunk/src/wrappers/StringToEnum/StringToEnum.h	(revision 15395)
+++ /issm/trunk/src/wrappers/StringToEnum/StringToEnum.h	(revision 15396)
@@ -18,13 +18,12 @@
 
 /*Header files: */
-#include "../../c/include/globals.h"
-#include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/shared/Enum/Enum.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
 #define __FUNCT__  "StringToEnum"
-    
+
 #ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
Index: /issm/trunk/src/wrappers/TriMesh/TriMesh.cpp
===================================================================
--- /issm/trunk/src/wrappers/TriMesh/TriMesh.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/TriMesh/TriMesh.cpp	(revision 15396)
@@ -6,25 +6,26 @@
 
 void TriMeshUsage(void){/*{{{*/
-	_printLine_("");
-	_printLine_("   usage: [index,x,y,segments,segmentmarkers]=TriMesh(domainoutlinefilename,rifts,area) ");
-	_printLine_("      where: index,x,y defines a triangulation, segments is an array made ");
-	_printLine_("      of exterior segments to the mesh domain outline, segmentmarkers is an array flagging each segment, ");
-	_printLine_("      outlinefilename an Argus domain outline file, ");
-	_printLine_("      area is the maximum area desired for any element of the resulting mesh, ");
-	_printLine_("");
+	_printf_("\n");
+	_printf_("   usage: [index,x,y,segments,segmentmarkers]=TriMesh(domainoutlinefilename,rifts,area) \n");
+	_printf_("      where: index,x,y defines a triangulation, segments is an array made \n");
+	_printf_("      of exterior segments to the mesh domain outline, segmentmarkers is an array flagging each segment, \n");
+	_printf_("      outlinefilename an Argus domain outline file, \n");
+	_printf_("      area is the maximum area desired for any element of the resulting mesh, \n");
+	_printf_("\n");
 }/*}}}*/
 WRAPPER(TriMesh){
-	
+
 	/*intermediary: */
-	double  area;
-	DataSet *domain = NULL;
-	DataSet *rifts  = NULL;
+	double    area;
+	Contours *domain = NULL;
+	Contours *rifts  = NULL;
 
 	/* output: */
-	SeqMat<int>    *index             = NULL;
-	SeqVec<double> *x                 = NULL;
-	SeqVec<double> *y                 = NULL;
-	SeqMat<int>    *segments          = NULL;
-	SeqVec<int>    *segmentmarkerlist = NULL;
+	int    *index             = NULL;
+	double *x                 = NULL;
+	double *y                 = NULL;
+	int    *segments          = NULL;
+	int    *segmentmarkerlist = NULL;
+	int     nels,nods,nsegs;
 
 	/*Boot module: */
@@ -33,5 +34,5 @@
 	/*checks on arguments: */
 	CHECKARGUMENTS(NLHS,NRHS,&TriMeshUsage);
-	
+
 	/*Fetch data needed for meshing: */
 	FetchData(&domain,DOMAINOUTLINE);
@@ -40,21 +41,21 @@
 
 	/*call x core: */
-	TriMeshx(&index,&x,&y,&segments,&segmentmarkerlist,domain,rifts,area);
+	TriMeshx(&index,&x,&y,&segments,&segmentmarkerlist,&nels,&nods,&nsegs,domain,rifts,area);
 
 	/*write outputs: */
-	WriteData(INDEX,index);
-	WriteData(X,x);
-	WriteData(Y,y);
-	WriteData(SEGMENTS,segments);
-	WriteData(SEGMENTMARKERLIST,segmentmarkerlist);
+	WriteData(INDEX,index,nels,3);
+	WriteData(X,x,nods);
+	WriteData(Y,y,nods);
+	WriteData(SEGMENTS,segments,nsegs,3);
+	WriteData(SEGMENTMARKERLIST,segmentmarkerlist,nsegs);
 
 	/*free ressources: */
 	delete domain;
 	delete rifts;
-	delete index;
-	delete x;
-	delete y;
-	delete segments;
-	delete segmentmarkerlist;
+	xDelete<int>(index);
+	xDelete<double>(x);
+	xDelete<double>(y);
+	xDelete<int>(segments);
+	xDelete<int>(segmentmarkerlist);
 
 	/*end module: */
Index: /issm/trunk/src/wrappers/TriMesh/TriMesh.h
===================================================================
--- /issm/trunk/src/wrappers/TriMesh/TriMesh.h	(revision 15395)
+++ /issm/trunk/src/wrappers/TriMesh/TriMesh.h	(revision 15396)
@@ -18,13 +18,11 @@
 
 /*Header files: */
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/toolkits/toolkits.h"
-#include "../../c/include/include.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
-#include "../../c/io/io.h"
-#include "../../c/EnumDefinitions/EnumDefinitions.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.cpp
===================================================================
--- /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 15396)
@@ -6,8 +6,8 @@
 
 void TriMeshProcessRiftsUsage(void){/*{{{*/
-	_printLine_("");
-	_printLine_("   usage: [index2,x2,y2,segments2,segmentmarkers2,rifts2]=TriMeshProcessrifts(index1,x1,y1,segments1,segmentmarkers1) ");
-	_printLine_("      where: (index1,x1,y1,segments1,segmentmarkers1) is an initial triangulation.");
-	_printLine_("      index2,x2,y2,segments2,segmentmarkers2,rifts2 is the resulting triangulation where rifts have been processed.");
+	_printf_("\n");
+	_printf_("   usage: [index2,x2,y2,segments2,segmentmarkers2,rifts2]=TriMeshProcessrifts(index1,x1,y1,segments1,segmentmarkers1) \n");
+	_printf_("      where: (index1,x1,y1,segments1,segmentmarkers1) is an initial triangulation.\n");
+	_printf_("      index2,x2,y2,segments2,segmentmarkers2,rifts2 is the resulting triangulation where rifts have been processed.\n");
 }/*}}}*/
 WRAPPER(TriMeshProcessRifts){
Index: /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.h
===================================================================
--- /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.h	(revision 15395)
+++ /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/TriaSearch/TriaSearch.cpp
===================================================================
--- /issm/trunk/src/wrappers/TriaSearch/TriaSearch.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/TriaSearch/TriaSearch.cpp	(revision 15396)
@@ -5,12 +5,12 @@
 
 void TriaSearchUsage(void){/*{{{*/
-	_pprintLine_("TriaSearch- find triangle holding a point (x0,y0) in a mesh");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("         tria=TriaSearch(index,x,y,x0,y0);");
-	_pprintLine_("      index,x,y: mesh triangulatrion");
-	_pprintLine_("      x0,y0: coordinates of the point for which we are trying to find a triangle");
-	_pprintLine_("      x0,y0 can be an array of points");
-	_pprintLine_("");
+	_printf0_("TriaSearch- find triangle holding a point (x0,y0) in a mesh\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("         tria=TriaSearch(index,x,y,x0,y0);\n");
+	_printf0_("      index,x,y: mesh triangulatrion\n");
+	_printf0_("      x0,y0: coordinates of the point for which we are trying to find a triangle\n");
+	_printf0_("      x0,y0 can be an array of points\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(TriaSearch){
Index: /issm/trunk/src/wrappers/TriaSearch/TriaSearch.h
===================================================================
--- /issm/trunk/src/wrappers/TriaSearch/TriaSearch.h	(revision 15395)
+++ /issm/trunk/src/wrappers/TriaSearch/TriaSearch.h	(revision 15396)
@@ -16,9 +16,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/Xy2ll/Xy2ll.cpp
===================================================================
--- /issm/trunk/src/wrappers/Xy2ll/Xy2ll.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/Xy2ll/Xy2ll.cpp	(revision 15396)
@@ -5,26 +5,26 @@
 
 void Xy2llUsage(void){/*{{{*/
-	_pprintLine_("Xy2ll - x/y to lat/long coordinate transformation module:");
-	_pprintLine_("");
-	_pprintLine_("   This module transforms x/y to lat/long coordinates.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [lat,lon]=Xy2ll(x,y,sgn,'param name',param,...);");
-	_pprintLine_("");
-	_pprintLine_("      x           x coordinates (double vector)");
-	_pprintLine_("      y           y coordinates (double vector)");
-	_pprintLine_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))");
-	_pprintLine_("");
-	_pprintLine_("      central_meridian     central meridian (double, optional, but must specify with sp)");
-	_pprintLine_("      standard_parallel    standard parallel (double, optional, but must specify with cm)");
-	_pprintLine_("");
-	_pprintLine_("      lat         latitude coordinates (double vector)");
-	_pprintLine_("      lon         longitude coordinates (double vector)");
-	_pprintLine_("");
-	_pprintLine_("   Examples:");
-	_pprintLine_("      [lat,lon]=Xy2ll(x,y, 1);");
-	_pprintLine_("      [lat,lon]=Xy2ll(x,y, 1,'central_meridian',45,'standard_parallel',70);");
-	_pprintLine_("      [lat,lon]=Xy2ll(x,y,-1,'central_meridian', 0,'standard_parallel',71);");
-	_pprintLine_("");
+	_printf0_("Xy2ll - x/y to lat/long coordinate transformation module:\n");
+	_printf0_("\n");
+	_printf0_("   This module transforms x/y to lat/long coordinates.\n");
+	_printf0_("\n");
+	_printf0_("   Usage:\n");
+	_printf0_("      [lat,lon]=Xy2ll(x,y,sgn,'param name',param,...);\n");
+	_printf0_("\n");
+	_printf0_("      x           x coordinates (double vector)\n");
+	_printf0_("      y           y coordinates (double vector)\n");
+	_printf0_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf0_("\n");
+	_printf0_("      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf0_("      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf0_("\n");
+	_printf0_("      lat         latitude coordinates (double vector)\n");
+	_printf0_("      lon         longitude coordinates (double vector)\n");
+	_printf0_("\n");
+	_printf0_("   Examples:\n");
+	_printf0_("      [lat,lon]=Xy2ll(x,y, 1);\n");
+	_printf0_("      [lat,lon]=Xy2ll(x,y, 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf0_("      [lat,lon]=Xy2ll(x,y,-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf0_("\n");
 }/*}}}*/
 WRAPPER(Xy2ll){
@@ -63,7 +63,7 @@
 	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
 		options->Get(&cm,"central_meridian");
-		if (verbose) _printLine_("  cm=" << cm);
+		if (verbose) _printf_("  cm=" << cm << "\n");
 		options->Get(&sp,"standard_parallel");
-		if (verbose) _printLine_("  sp=" << sp);
+		if (verbose) _printf_("  sp=" << sp << "\n");
 	}
 
@@ -79,5 +79,5 @@
 
 	/* Run core computations: */
-	if (verbose) _printLine_("Calling core:");
+	if (verbose) _printf_("Calling core:\n");
 	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
 		iret=Xy2llx(lat,lon,x,y,ncoord,sgn,cm,sp);
Index: /issm/trunk/src/wrappers/Xy2ll/Xy2ll.h
===================================================================
--- /issm/trunk/src/wrappers/Xy2ll/Xy2ll.h	(revision 15395)
+++ /issm/trunk/src/wrappers/Xy2ll/Xy2ll.h	(revision 15396)
@@ -17,9 +17,8 @@
 #endif
 
-#include "../../c/include/globals.h"
+#include "../bindings.h"
+#include "../../c/main/globals.h"
 #include "../../c/modules/modules.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../bindings.h"
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/wrappers/bindings.h
===================================================================
--- /issm/trunk/src/wrappers/bindings.h	(revision 15395)
+++ /issm/trunk/src/wrappers/bindings.h	(revision 15396)
@@ -8,4 +8,10 @@
 #endif
 
+#ifdef  _HAVE_PYTHON_MODULES_
+#include "./python/include/pythonincludes.h"
+#include "./python/include/wrapper_macros.h"
+#include "./python/io/pythonio.h"
+#endif
+
 #ifdef  _HAVE_MATLAB_MODULES_
 #include "./matlab/include/matlabincludes.h"
@@ -14,9 +20,3 @@
 #endif
 
-#ifdef  _HAVE_PYTHON_MODULES_
-#include "./python/include/pythonincludes.h"
-#include "./python/include/wrapper_macros.h"
-#include "./python/io/pythonio.h"
 #endif
-
-#endif
Index: /issm/trunk/src/wrappers/matlab/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 15396)
@@ -23,6 +23,7 @@
 				./io/MatlabVectorToDoubleVector.cpp\
 				./io/MatlabMatrixToDoubleMatrix.cpp\
-				./io/MatlabMatrixToSeqMat.cpp\
-				./io/MatlabVectorToSeqVec.cpp
+				./io/MatlabMatrixToIssmMat.cpp\
+				./io/MatlabVectorToIssmVec.cpp
+
 				
 if PETSC
@@ -36,4 +37,20 @@
 if SHAREDLIBS
 libISSMMatlab_la_SOURCES = $(io_sources)
+endif
+#}}}
+#api io{{{
+lib_LIBRARIES += libISSMApi.a 
+if SHAREDLIBS
+lib_LTLIBRARIES += libISSMApi.la
+else
+lib_LTLIBRARIES +=
+endif
+
+api_sources= ./io/ApiPrintf.cpp
+
+libISSMApi_a_SOURCES = $(api_sources)
+libISSMApi_a_CXXFLAGS= $(ALLCXXFLAGS)
+if SHAREDLIBS
+libISSMApi_la_SOURCES = $(api_sources)
 endif
 #}}}
@@ -46,4 +63,5 @@
 						 ContourToMesh.la\
 						 ContourToNodes.la\
+						 EdgeDetection.la\
 						 ElementConnectivity.la\
 						 EnumToString.la\
@@ -84,12 +102,7 @@
 endif 
 #}}}
-#Flags and libraries {{{
-#if SHAREDLIBS
-#deps = ../../c/libISSMCore.la ../../c/libISSMModules.la
-#else
-#deps = ../../c/libISSMCore.a ../../c/libISSMModules.a
-#endif
-#deps +=  $(MATHLIB) ${MEXLIB}
-deps =  $(MATHLIB) ${MEXLIB}
+
+# Dependencies {{{
+deps =  $(MATHLIB)
 
 #Triangle library
@@ -103,171 +116,179 @@
 AM_LDFLAGS += -avoid-version
 endif
-if SHAREDLIBS
-deps += ./libISSMMatlab.la 
-else
-deps += ./libISSMMatlab.a
-AM_LDFLAGS += --no-warnings 
-endif
 
 AM_CXXFLAGS +=  -D_HAVE_MATLAB_MODULES_  -D_GNU_SOURCE -fPIC -fno-omit-frame-pointer -pthread 
 
 if SHAREDLIBS
-deps +=
-else
-deps += ../../c/libISSMModules.a ../../c/libISSMCore.a  
+deps += ../../c/libISSMModules.la ../../c/libISSMCore.la ./libISSMApi.la ./libISSMMatlab.a
+else
+deps += ./libISSMMatlab.a ../../c/libISSMModules.a ../../c/libISSMCore.a ./libISSMApi.a
 if ADOLC
 deps += $(ADOLCLIB)
 endif
 endif
+
+#MEXLIB needs to be the last (undefined references on larsen)
+deps += ${MEXLIB}
+
 #Optimization flags:
 AM_CXXFLAGS += $(CXXOPTFLAGS) 
 #}}}
-#Bin sources {{{
+# Module sources and dependencies {{{
+libISSMMatlab_la_LIBADD = $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MATHLIB) $(MEXLIB) ./../../c/libISSMCore.la
+libISSMMatlab_la_LDFLAGS = -module
+
+libISSMApi_la_LIBADD = $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MATHLIB) $(MEXLIB)
+libISSMApi_la_LDFLAGS = -module
+
 AverageFilter_la_SOURCES = ../AverageFilter/AverageFilter.cpp\
 									../AverageFilter/AverageFilter.h
-AverageFilter_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+AverageFilter_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
 								../BamgMesher/BamgMesher.h
-BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
 									  ../BamgConvertMesh/BamgConvertMesh.h
-BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 BamgTriangulate_la_SOURCES = ../BamgTriangulate/BamgTriangulate.cpp\
 									  ../BamgTriangulate/BamgTriangulate.h
-BamgTriangulate_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+BamgTriangulate_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 Chaco_la_SOURCES = ../Chaco/Chaco.cpp\
 						 ../Chaco/Chaco.h
-Chaco_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(CHACOLIB)
+Chaco_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(CHACOLIB) $(GSLLIB)
 
 ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
 									../ContourToMesh/ContourToMesh.h
-ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
 
 ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
 									 ../ContourToNodes/ContourToNodes.h
-ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
 											../ElementConnectivity/ElementConnectivity.h
-ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp\
 								  ../EnumToString/EnumToString.h
-EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp\
 								  ../StringToEnum/StringToEnum.h
-StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 HoleFiller_la_SOURCES = ../HoleFiller/HoleFiller.cpp\
 								../HoleFiller/HoleFiller.h
-HoleFiller_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) 
+HoleFiller_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)  $(GSLLIB)
 
 InternalFront_la_SOURCES = ../InternalFront/InternalFront.cpp\
 									../InternalFront/InternalFront.h
-InternalFront_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+InternalFront_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
 											 ../InterpFromGridToMesh/InterpFromGridToMesh.h
-InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
 
 InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
 												../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
-InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
 
 InterpFromMeshToMesh3d_la_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
 												../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
-InterpFromMeshToMesh3d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+InterpFromMeshToMesh3d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 InterpFromMeshToGrid_la_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
 											 ../InterpFromMeshToGrid/InterpFromMeshToGrid.h
-InterpFromMeshToGrid_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+InterpFromMeshToGrid_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 InterpFromMesh2d_la_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp\
 										../InterpFromMesh2d/InterpFromMesh2d.h
-InterpFromMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+InterpFromMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
 
 KMLFileRead_la_SOURCES = ../KMLFileRead/KMLFileRead.cpp\
 								 ../KMLFileRead/KMLFileRead.h
-KMLFileRead_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+KMLFileRead_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 KMLMeshWrite_la_SOURCES = ../KMLMeshWrite/KMLMeshWrite.cpp\
 								  ../KMLMeshWrite/KMLMeshWrite.h
-KMLMeshWrite_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+KMLMeshWrite_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 KMLOverlay_la_SOURCES = ../KMLOverlay/KMLOverlay.cpp\
 								../KMLOverlay/KMLOverlay.h
-KMLOverlay_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+KMLOverlay_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 Xy2ll_la_SOURCES = ../Xy2ll/Xy2ll.cpp\
 						 ../Xy2ll/Xy2ll.h
-Xy2ll_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+Xy2ll_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 Ll2xy_la_SOURCES = ../Ll2xy/Ll2xy.cpp\
 						 ../Ll2xy/Ll2xy.h
-Ll2xy_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+Ll2xy_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+
+EdgeDetection_la_SOURCES = ../EdgeDetection/EdgeDetection.cpp\
+							../EdgeDetection/EdgeDetection.h
+EdgeDetection_la_LIBADD= ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 ExpSimplify_la_SOURCES = ../ExpSimplify/ExpSimplify.cpp\
 							../ExpSimplify/ExpSimplify.h
-ExpSimplify_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+ExpSimplify_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 Exp2Kml_la_SOURCES = ../Exp2Kml/Exp2Kml.cpp\
 							../Exp2Kml/Exp2Kml.h
-Exp2Kml_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+Exp2Kml_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 Kml2Exp_la_SOURCES = ../Kml2Exp/Kml2Exp.cpp\
 							../Kml2Exp/Kml2Exp.h
-Kml2Exp_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+Kml2Exp_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 Kriging_la_SOURCES = ../Kriging/Kriging.cpp\
 							../Kriging/Kriging.h
-Kriging_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MULTITHREADINGLIB)
+Kriging_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MULTITHREADINGLIB) $(GSLLIB)
 
 MeshPartition_la_SOURCES = ../MeshPartition/MeshPartition.cpp\
 									../MeshPartition/MeshPartition.h
-MeshPartition_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(METISLIB)
+MeshPartition_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(METISLIB) $(GSLLIB)
 
 MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
 												 ../MeshProfileIntersection/MeshProfileIntersection.h
-MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
 										../NodeConnectivity/NodeConnectivity.h
-NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 PointCloudFindNeighbors_la_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp\
 												 ../PointCloudFindNeighbors/PointCloudFindNeighbors.h
-PointCloudFindNeighbors_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+PointCloudFindNeighbors_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
 
 PropagateFlagsFromConnectivity_la_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp\
 														  ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
-PropagateFlagsFromConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+PropagateFlagsFromConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 Scotch_la_SOURCES = ../Scotch/Scotch.cpp\
 						  ../Scotch/Scotch.h
-Scotch_la_LIBADD = ${deps} $(SCOTCHLIB) $(MPILIB)
+Scotch_la_LIBADD = ${deps} $(SCOTCHLIB) $(MPILIB) $(BLASLAPACKLIB)
 
 Shp2Exp_la_SOURCES = ../Shp2Exp/Shp2Exp.cpp\
 							../Shp2Exp/Shp2Exp.h
-Shp2Exp_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB)
+Shp2Exp_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 Shp2Kml_la_SOURCES = ../Shp2Kml/Shp2Kml.cpp\
 							../Shp2Kml/Shp2Kml.h
-Shp2Kml_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB)
+Shp2Kml_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 TriaSearch_la_SOURCES = ../TriaSearch/TriaSearch.cpp\
 								../TriaSearch/TriaSearch.h
-TriaSearch_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+TriaSearch_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp\
 							../TriMesh/TriMesh.h
-TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB)
+TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB)
 
 TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
 											../TriMeshProcessRifts/TriMeshProcessRifts.h
-TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
-#}}}
+TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+#}}}
Index: /issm/trunk/src/wrappers/matlab/io/ApiPrintf.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/ApiPrintf.cpp	(revision 15396)
+++ /issm/trunk/src/wrappers/matlab/io/ApiPrintf.cpp	(revision 15396)
@@ -0,0 +1,19 @@
+/* \file ApiPrintf.c:
+ * \brief: API specific symbols from libISSMCore that we need to resolve here
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./matlabio.h"
+
+/*Matlab printf i/o: */
+void ApiPrintf(const char* string){
+
+	/*use mexPrintf in matlab: */
+	mexPrintf(string);
+	return;
+}
Index: /issm/trunk/src/wrappers/matlab/io/CheckNumMatlabArguments.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/CheckNumMatlabArguments.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/CheckNumMatlabArguments.cpp	(revision 15396)
@@ -4,5 +4,4 @@
 
 #include "./matlabio.h"
-#include "../../c/shared/Exceptions/exceptions.h"
 
 int CheckNumMatlabArguments(int nlhs,int NLHS, int nrhs,int NRHS, const char* THISFUNCTION, void (*function)( void )){
Index: /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp	(revision 15396)
@@ -10,5 +10,4 @@
 
 #include "./matlabio.h"
-#include "../../c/shared/shared.h"
 
 /*Primitive data types*/
@@ -38,5 +37,5 @@
 		else{
 			if(!mxIsClass(dataref,"double") && !mxIsClass(dataref,"single")){
-				_printLine_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'");
+				_printf_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'\n");
 			}
 			/*Convert matlab matrix to double* matrix: */
@@ -85,5 +84,5 @@
 		else{
 			if(!mxIsClass(dataref,"double") && !mxIsClass(dataref,"single")){
-				_printLine_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'");
+				_printf_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'\n");
 			}
 			/*Convert matlab n-dim array to double* matrix: */
@@ -132,5 +131,5 @@
 		else{
 			if(!mxIsClass(dataref,"double") && !mxIsClass(dataref,"single")){
-				_printLine_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'");
+				_printf_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'\n");
 			}
 			/*Convert matlab matrix to double* matrix: */
@@ -635,24 +634,24 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(DataSet** pcontours,const mxArray* dataref){{{*/
-void FetchData(DataSet** pcontours,const mxArray* dataref){
-
-	int              numcontours,index,test1,test2;
+/*FUNCTION FetchData(Contours** pcontours,const mxArray* dataref){{{*/
+void FetchData(Contours** pcontours,const mxArray* dataref){
+
+	int             numcontours,index,test1,test2;
 	char            *contourname = NULL;
-	DataSet         *contours    = NULL;
+	Contours        *contours    = NULL;
 	Contour<double> *contouri    = NULL;
 
 	if (mxIsClass(dataref,"char")){
 		FetchData(&contourname,dataref);
-		contours=DomainOutlineRead<double>(contourname);
+		contours=ExpRead<double>(contourname);
 	}
 	else if(mxIsClass(dataref,"struct")){
 
-		contours=new DataSet(0);
+		contours=new Contours();
 		numcontours=mxGetNumberOfElements(dataref);
 
 		for(int i=0;i<numcontours;i++){
 
-			contouri=xNew<Contour<double> >(1);
+			contouri=new Contour<double>();
 
 			index = mxGetFieldNumber(dataref,"nods");
Index: /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToDoubleMatrix.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 15396)
@@ -11,5 +11,4 @@
 /*Matlab includes: */
 #include "./matlabio.h"
-#include "../../c/shared/shared.h"
 
 int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
Index: /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToIssmMat.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToIssmMat.cpp	(revision 15396)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToIssmMat.cpp	(revision 15396)
@@ -0,0 +1,21 @@
+/*!\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: /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToMatrix.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToMatrix.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToMatrix.cpp	(revision 15396)
@@ -8,9 +8,5 @@
 #endif
 
-#include <stdio.h>
-#include <string.h>
 #include "./matlabio.h"
-#include "../../c/shared/shared.h"
-#include "../../c/toolkits/toolkits.h"
 
 Matrix<double>* MatlabMatrixToMatrix(const mxArray* mxmatrix){
@@ -25,5 +21,5 @@
 	matrix->pmatrix=MatlabMatrixToPetscMat(mxmatrix);
 	#else
-	matrix->smatrix=MatlabMatrixToSeqMat(mxmatrix);
+	matrix->imatrix=MatlabMatrixToIssmMat(mxmatrix);
 	#endif
 
Index: sm/trunk/src/wrappers/matlab/io/MatlabMatrixToSeqMat.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToSeqMat.cpp	(revision 15395)
+++ 	(revision )
@@ -1,25 +1,0 @@
-/*!\file MatlabMatrixToSeqMat.cpp
- */
-
-/*Headers:*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include <stdio.h>
-#include <string.h>
-#include "./matlabio.h"
-#include "../../c/toolkits/toolkits.h"
-#include "../../c/shared/shared.h"
-
-SeqMat<double>* MatlabMatrixToSeqMat(const mxArray* dataref){
-
-	SeqMat<double>* output=NULL;
-
-	output=new SeqMat<double>();
-	MatlabMatrixToDoubleMatrix(&output->matrix,&output->M,&output->N,dataref);
-	return output;
-
-}
Index: /issm/trunk/src/wrappers/matlab/io/MatlabNArrayToNArray.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabNArrayToNArray.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabNArrayToNArray.cpp	(revision 15396)
@@ -10,6 +10,4 @@
 
 #include "./matlabio.h"
-#include "../../c/shared/shared.h"
-#include "../../c/include/include.h"
 
 /*FUNCTION MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
Index: /issm/trunk/src/wrappers/matlab/io/MatlabVectorToDoubleVector.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 15396)
@@ -9,9 +9,6 @@
 #endif
 
-#include <string.h>
-
 /*Matlab includes: */
 #include "./matlabio.h"
-#include "../../c/shared/shared.h"
 
 int MatlabVectorToDoubleVector(double** pvector,int* pvector_rows,const mxArray* mxvector){
Index: /issm/trunk/src/wrappers/matlab/io/MatlabVectorToIssmSeqVec.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToIssmSeqVec.cpp	(revision 15396)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabVectorToIssmSeqVec.cpp	(revision 15396)
@@ -0,0 +1,15 @@
+/*!\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: /issm/trunk/src/wrappers/matlab/io/MatlabVectorToIssmVec.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToIssmVec.cpp	(revision 15396)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabVectorToIssmVec.cpp	(revision 15396)
@@ -0,0 +1,21 @@
+/*!\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: /issm/trunk/src/wrappers/matlab/io/MatlabVectorToPetscVec.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToPetscVec.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabVectorToPetscVec.cpp	(revision 15396)
@@ -9,12 +9,6 @@
 #endif
 
-/*Petsc includes: */
-#include <petscmat.h>
-#include <petscvec.h>
-#include <petscksp.h>
-
 /*Matlab includes: */
 #include "./matlabio.h"
-#include "../../c/shared/shared.h"
 
 PetscVec* MatlabVectorToPetscVec(const mxArray* mxvector){
Index: sm/trunk/src/wrappers/matlab/io/MatlabVectorToSeqVec.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToSeqVec.cpp	(revision 15395)
+++ 	(revision )
@@ -1,20 +1,0 @@
-/*!\file MatlabVectorToSeqVec.cpp
- */
-
-/*Headers:*/
-#include <mex.h>
-#include <stdio.h>
-#include <string.h>
-#include "./matlabio.h"
-#include "../../c/toolkits/toolkits.h"
-#include "../../c/shared/shared.h"
-
-SeqVec<double>* MatlabVectorToSeqVec(const mxArray* dataref){
-
-	SeqVec<double>* output=NULL;
-
-	output=new SeqVec<double>();
-	MatlabVectorToDoubleVector(&output->vector,&output->M,dataref);
-	return output;
-
-}
Index: /issm/trunk/src/wrappers/matlab/io/MatlabVectorToVector.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToVector.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabVectorToVector.cpp	(revision 15396)
@@ -8,9 +8,5 @@
 #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
-#include <stdio.h>
-#include <string.h>
 #include "./matlabio.h"
-#include "../../c/shared/shared.h"
-#include "../../c/toolkits/toolkits.h"
 
 Vector<double>* MatlabVectorToVector(const mxArray* mxvector){
@@ -25,5 +21,5 @@
 	vector->pvector=MatlabVectorToPetscVec(mxvector);
 	#else
-	vector->svector=MatlabVectorToSeqVec(mxvector);
+	vector->ivector=MatlabVectorToIssmVec(mxvector);
 	#endif
 
Index: /issm/trunk/src/wrappers/matlab/io/OptionParse.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/OptionParse.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/OptionParse.cpp	(revision 15396)
@@ -10,6 +10,4 @@
 #include <cstring> 
 #include "./matlabio.h"
-#include "../../c/shared/shared.h"
-#include "../../c/io/io.h"
 
 GenericOption<double>* OptionDoubleParse( char* name, const mxArray* prhs[]){ /*{{{*/
@@ -190,5 +188,5 @@
 	 option=(Option*)OptionCellParse(name,prhs);
 	else {
-		_pprintLine_("  Converting value of option \"" << name << "\" from unrecognized class \"" << mxGetClassName(prhs[0]) << "\" to class \"" << "struct" << "\".");
+		_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);
Index: /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp	(revision 15396)
@@ -10,5 +10,5 @@
 
 #include "./matlabio.h"
-#include "../../c/shared/shared.h"
+#include "./../../../c/datastructures/datastructures.h"
 
 /*Primitive data types*/
@@ -74,4 +74,27 @@
 		vector_matlab=(double*)mxMalloc(M*sizeof(double));
 		for(int i=0;i<M;i++) vector_matlab[i]=vector[i];
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(dataref,(mwSize)M);
+		mxSetN(dataref,(mwSize)1);
+		mxSetPr(dataref,vector_matlab);
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,int* vector, int M){{{*/
+void WriteData(mxArray** pdataref,int* vector, int M){
+
+	mxArray* dataref       = NULL;
+	double*  vector_matlab = NULL;
+
+	if(vector){
+
+		/*create the matlab vector with Matlab's memory manager */
+		vector_matlab=(double*)mxMalloc(M*sizeof(double));
+		for(int i=0;i<M;i++) vector_matlab[i]=double(vector[i]);
 		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
 		mxSetM(dataref,(mwSize)M);
@@ -221,6 +244,6 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,SeqMat<double>* matrix){{{*/
-void WriteData(mxArray** pdataref,SeqMat<double>* matrix){
+/*FUNCTION WriteData(mxArray** pdataref,IssmDenseMat<double>* matrix){{{*/
+void WriteData(mxArray** pdataref,IssmDenseMat<double>* matrix){
 
 	int      i,j;
@@ -259,6 +282,6 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,SeqVec<double>* vector){{{*/
-void WriteData(mxArray** pdataref,SeqVec<double>* vector){
+/*FUNCTION WriteData(mxArray** pdataref,IssmSeqVec<double>* vector){{{*/
+void WriteData(mxArray** pdataref,IssmSeqVec<double>* vector){
 
 	mxArray* dataref=NULL;
@@ -287,73 +310,4 @@
 	/*Clean-up and return*/
 	xDelete<double>(vector_ptr);
-	*pdataref=dataref;
-}
-/*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,SeqMat<int>* matrix){{{*/
-void WriteData(mxArray** pdataref,SeqMat<int>* matrix){
-
-	int      i,j;
-	int      rows,cols;
-	mxArray *dataref     = NULL;
-	int     *matrix_ptr  = NULL;
-	double  *tmatrix_ptr = NULL;
-
-	if(matrix){
-
-		matrix_ptr=matrix->ToSerial();
-		matrix->GetSize(&rows,&cols);
-
-		/*Now transpose the matrix and allocate with Matlab's memory manager: */
-		tmatrix_ptr=(double*)mxMalloc(rows*cols*sizeof(double));
-		for(i=0;i<rows;i++){
-			for(j=0;j<cols;j++){
-				tmatrix_ptr[j*rows+i]=(double)matrix_ptr[i*cols+j];
-			}
-		}
-
-		/*create matlab matrix: */
-		dataref=mxCreateDoubleMatrix(0,0,mxREAL);
-		mxSetM(dataref,rows); 
-		mxSetN(dataref,cols);
-		mxSetPr(dataref,tmatrix_ptr);
-
-		/*Free ressources:*/
-		xDelete<int>(matrix_ptr);
-	}
-	else{
-		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
-	}
-
-	*pdataref=dataref;
-}
-/*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,SeqVec<int>* vector){{{*/
-void WriteData(mxArray** pdataref,SeqVec<int>* vector){
-
-	mxArray* dataref=NULL;
-	int*     vector_ptr=NULL;
-	double*  vector_matlab=NULL;
-	int      rows;
-
-	if(vector){
-		/*call toolkit routine: */
-		vector_ptr=vector->ToMPISerial();
-		vector->GetSize(&rows);
-
-		/*now create the matlab vector with Matlab's memory manager */
-		vector_matlab=(double*)mxMalloc(rows*sizeof(double));
-		for(int i=0;i<rows;i++) vector_matlab[i]=(double)vector_ptr[i];
-
-		dataref = mxCreateDoubleMatrix(0,0,mxREAL);                         
-		mxSetM(dataref,rows);
-		mxSetN(dataref,1);                                                                                          
-		mxSetPr(dataref,vector_matlab);           
-	}
-	else{
-		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
-	}
-
-	/*Clean-up and return*/
-	xDelete<int>(vector_ptr);
 	*pdataref=dataref;
 }
@@ -406,7 +360,60 @@
 }
 /*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,Contours* contours){{{*/
+void WriteData(mxArray** pdataref,Contours* contours){
+
+	/*Intermediary*/
+
+	int         i;
+	mxArray    *dataref           = NULL;
+	const int   numfields         = 6;
+	const char *fnames[numfields];
+	mwSize      ndim              = 2;
+	mwSize      dimensions[2]     = {1,1};
+	char        id[100];
+
+	/*Initialize field names*/
+	i=0;
+	fnames[i++] = "name";
+	fnames[i++] = "nods";
+	fnames[i++] = "density";
+	fnames[i++] = "x";
+	fnames[i++] = "y";
+	fnames[i++] = "closed";
+	_assert_(i==numfields);
+
+	/*Initialize matlab structure of dimension numrifts*/
+	dimensions[0]=contours->Size();
+	dataref=mxCreateStructArray(ndim,dimensions,numfields,fnames);
+
+	/*set each matlab each field*/
+	for(int i=0;i<contours->Size();i++){
+		Contour<IssmPDouble>* contour=(Contour<IssmPDouble>*)contours->GetObjectByOffset(i);
+
+		/*create a name for this contour from the contour id and set it: */
+		sprintf(id,"%i",contour->id);
+		SetStructureFieldi(dataref,i,"name",id);
+
+		/*number of nods: */
+		SetStructureFieldi(dataref,i,"nods"         ,contour->nods);
+
+		/*density: */
+		SetStructureFieldi(dataref,i,"density"            ,1);
+
+		/*x and y: */
+		SetStructureFieldi(dataref,i,"x"             ,contour->nods, 1,contour->x);
+		SetStructureFieldi(dataref,i,"y"             ,contour->nods, 1,contour->y);
+
+		/*closed: */
+		SetStructureFieldi(dataref,i,"closed"         ,(int)contour->closed);
+	}
+
+	/*Assign output*/
+	*pdataref=dataref;
+}
+/*}}}*/
 
 /*Toolkit*/
-/*FUNCTION SetStructureField{{{*/
+/*FUNCTION SetStructureField(mxArray* dataref,const char* fieldname,int M,int N,double* fieldpointer){{{*/
 void SetStructureField(mxArray* dataref,const char* fieldname,int M,int N,double* fieldpointer){
 
@@ -418,4 +425,16 @@
 	/*Assign to structure*/
 	mxSetField(dataref,0,fieldname,field);
+}
+/*}}}*/
+/*FUNCTION SetStructureFieldi(mxArray* dataref,const char* fieldname,char* string) {{{*/
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,char* string){
+
+	mxArray* field = NULL;
+
+	/*Convert field*/
+	WriteData(&field,string);
+
+	/*Assign to structure*/
+	mxSetField(dataref,i,fieldname,field);
 }
 /*}}}*/
Index: /issm/trunk/src/wrappers/matlab/io/matlabio.h
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/matlabio.h	(revision 15395)
+++ /issm/trunk/src/wrappers/matlab/io/matlabio.h	(revision 15396)
@@ -13,15 +13,15 @@
 
 #include "../include/matlabincludes.h"
-#include "../../c/classes/classes.h"
-#include "../../c/Container/Container.h"
-#include "../../c/include/include.h"
+#include "../../../c/bamg/bamgobjects.h"
+#include "../../../c/classes/classes.h"
+#include "../../../c/toolkits/toolkits.h"
+#include "../../../c/shared/shared.h"
 
-void WriteData(mxArray** pdataref,SeqMat<int>* matrix);
-void WriteData(mxArray** pdataref,SeqMat<double>* matrix);
+void WriteData(mxArray** pdataref,IssmDenseMat<double>* matrix);
 void WriteData(mxArray** pdataref,double* matrix, int M,int N);
 void WriteData(mxArray** pdataref,int*    matrix, int M,int N);
-void WriteData(mxArray** pdataref,SeqVec<int>* vector);
-void WriteData(mxArray** pdataref,SeqVec<double>* vector);
+void WriteData(mxArray** pdataref,IssmSeqVec<double>* vector);
 void WriteData(mxArray** pdataref,double* vector, int M);
+void WriteData(mxArray** pdataref,int* vector, int M);
 void WriteData(mxArray** pdataref,int integer);
 void WriteData(mxArray** pdataref,bool boolean);
@@ -32,4 +32,5 @@
 void WriteData(mxArray** pdataref,BamgMesh* bamgmesh);
 void WriteData(mxArray** pdataref,RiftStruct* riftstruct);
+void WriteData(mxArray** pdataref,Contours* contours);
 
 void FetchData(double** pmatrix,int* pM,int *pN,const mxArray* dataref);
@@ -53,5 +54,5 @@
 void FetchData(BamgOpts** bamgopts,const mxArray* dataref);
 void FetchData(Options** poptions,int istart, int nrhs,const mxArray** pdataref);
-void FetchData(DataSet** pcontours,const mxArray* dataref);
+void FetchData(Contours** pcontours,const mxArray* dataref);
 
 Option* OptionParse(char* name, const mxArray* prhs[]);
@@ -69,4 +70,5 @@
 void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,int field);
 void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,double field);
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,char* string);
 int CheckNumMatlabArguments(int nlhs,int NLHS, int nrhs,int NRHS, const char* THISFUNCTION, void (*function)( void ));
 
@@ -82,7 +84,7 @@
 int MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix);
 
-/*Matlab to SeqMat routines: */
-SeqMat<double>* MatlabMatrixToSeqMat(const mxArray* dataref);
-SeqVec<double>* MatlabVectorToSeqVec(const mxArray* dataref);
+/*Matlab to IssmDenseMat routines: */
+IssmMat<double>* MatlabMatrixToIssmMat(const mxArray* dataref);
+IssmVec<double>* MatlabVectorToIssmVec(const mxArray* dataref);
 
 /*Matlab to Petsc routines: */
@@ -94,3 +96,5 @@
 #endif
 
+/*Print*/
+void ApiPrintf(const char* string);
 #endif	/* _IO_H_ */
Index: /issm/trunk/src/wrappers/python/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/python/Makefile.am	(revision 15395)
+++ /issm/trunk/src/wrappers/python/Makefile.am	(revision 15396)
@@ -8,5 +8,5 @@
 lib_LTLIBRARIES = libISSMPython.la
 else
-	lib_LTLIBRARIES =
+lib_LTLIBRARIES =
 endif
 
@@ -22,4 +22,20 @@
 if SHAREDLIBS
 libISSMPython_la_SOURCES = $(io_sources)
+endif
+#}}}
+#api io{{{
+lib_LIBRARIES += libISSMApi.a 
+if SHAREDLIBS
+lib_LTLIBRARIES += libISSMApi.la
+else
+lib_LTLIBRARIES +=
+endif
+
+api_sources= ./io/ApiPrintf.cpp
+
+libISSMApi_a_SOURCES = $(api_sources)
+libISSMApi_a_CXXFLAGS= $(ALLCXXFLAGS)
+if SHAREDLIBS
+libISSMApi_la_SOURCES = $(api_sources)
 endif
 #}}}
@@ -80,4 +96,12 @@
 endif
 
+if SHAREDLIBS
+deps += ./libISSMApi.la 
+else
+deps += ./libISSMApi.a
+endif
+
+
+
 endif 
 
@@ -88,52 +112,52 @@
 BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
 									  ../BamgConvertMesh/BamgConvertMesh.h
-BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
 								../BamgMesher/BamgMesher.h
-BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
 									 ../ContourToMesh/ContourToMesh.h
-ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
 									 ../ContourToNodes/ContourToNodes.h
-ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
 											../ElementConnectivity/ElementConnectivity.h
-ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp\
 								  ../EnumToString/EnumToString.h
-EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
 												../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
-InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
 
 InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
 												../InterpFromGridToMesh/InterpFromGridToMesh.h
-InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
 
 MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
 										../MeshProfileIntersection/MeshProfileIntersection.h
-MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
 										../NodeConnectivity/NodeConnectivity.h
-NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp\
 								  ../StringToEnum/StringToEnum.h
-StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 
 TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp\
 							../TriMesh/TriMesh.h
-TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB)
+TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB)
 
 TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
 											../TriMeshProcessRifts/TriMeshProcessRifts.h
-TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
 #}}}
Index: /issm/trunk/src/wrappers/python/io/ApiPrintf.cpp
===================================================================
--- /issm/trunk/src/wrappers/python/io/ApiPrintf.cpp	(revision 15396)
+++ /issm/trunk/src/wrappers/python/io/ApiPrintf.cpp	(revision 15396)
@@ -0,0 +1,21 @@
+/* \file ApiPrintf.c:
+ * \brief: pyton api specific symbols which are unresolved from libISSMCore.a
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./pythonio.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/Enum/Enum.h"
+
+/*Python printf i/o: */
+void ApiPrintf(const char* string){
+
+	/*use printf: */
+	printf("%s",string);
+	return;
+}
Index: /issm/trunk/src/wrappers/python/io/CheckNumPythonArguments.cpp
===================================================================
--- /issm/trunk/src/wrappers/python/io/CheckNumPythonArguments.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/python/io/CheckNumPythonArguments.cpp	(revision 15396)
@@ -8,5 +8,4 @@
 #include "./pythonio.h"
 #include "../../c/shared/Exceptions/exceptions.h"
-#include "../../c/include/include.h"
 
 int CheckNumPythonArguments(PyObject* inputs,int NRHS, void (*function)( void )){
Index: /issm/trunk/src/wrappers/python/io/FetchPythonData.cpp
===================================================================
--- /issm/trunk/src/wrappers/python/io/FetchPythonData.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/python/io/FetchPythonData.cpp	(revision 15396)
@@ -13,5 +13,4 @@
 
 #include "./pythonio.h"
-#include "../../c/include/include.h"
 #include "../../c/shared/shared.h"
 
@@ -104,4 +103,5 @@
 	bool* bmatrix=NULL;
 	int i;
+	PyObject* py_matrix2=NULL;
 
 	if     (PyArray_Check((PyArrayObject*)py_matrix)) {
@@ -120,4 +120,9 @@
 
 		if (M && N) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_matrix)) {
+				py_matrix2=PyArray_ContiguousFromAny(py_matrix,NPY_DOUBLE,ndim,ndim);
+				py_matrix=py_matrix2;
+			}
+
 			if      (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_DOUBLE) {
 				/*retrieve internal value: */
@@ -126,8 +131,27 @@
 				/*copy matrix: */
 				matrix=xNew<double>(M*N);
-				memcpy(matrix,dmatrix,(M*N)*sizeof(double));
-			}
-
-			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_INT64) {
+//				if (PyArray_ISCONTIGUOUS((PyArrayObject*)py_matrix)) {
+					memcpy(matrix,dmatrix,(M*N)*sizeof(double));
+//				}
+
+//				else {
+//					int j,k,ipt=0;
+//					int mstride,nstride;
+//					mstride=(int)PyArray_STRIDE((PyArrayObject*)py_matrix,0)/PyArray_ITEMSIZE((PyArrayObject*)py_matrix);
+//					if (ndim > 1)
+//						nstride=(int)PyArray_STRIDE((PyArrayObject*)py_matrix,1)/PyArray_ITEMSIZE((PyArrayObject*)py_matrix);
+//					else
+//						nstride=1;
+//					for (i=0; i<M; i++) {
+//						k=i*mstride;
+//						for (j=0; j<N; j++) {
+//							matrix[ipt++]=dmatrix[k];
+//							k+=nstride;
+//						}
+//					}
+//				}
+			}
+
+			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_LONG) {
 				/*retrieve internal value: */
 				lmatrix=(long*)PyArray_DATA((PyArrayObject*)py_matrix);
@@ -149,4 +173,7 @@
 			else
 				_error_("unrecognized double pyarray type in input!");
+
+			if (py_matrix2)
+				delete(py_matrix2);
 		}
 		else
@@ -181,4 +208,5 @@
 	bool* bmatrix=NULL;
 	int i;
+	PyObject* py_matrix2=NULL;
 
 	if     (PyArray_Check((PyArrayObject*)py_matrix)) {
@@ -197,4 +225,9 @@
 
 		if (M && N) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_matrix)) {
+				py_matrix2=PyArray_ContiguousFromAny(py_matrix,NPY_LONG,ndim,ndim);
+				py_matrix=py_matrix2;
+			}
+
 			if      (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_DOUBLE) {
 				/*retrieve internal value: */
@@ -206,5 +239,5 @@
 			}
 
-			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_INT64) {
+			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_LONG) {
 				/*retrieve internal value: */
 				lmatrix=(long*)PyArray_DATA((PyArrayObject*)py_matrix);
@@ -226,4 +259,7 @@
 			else
 				_error_("unrecognized int pyarray type in input!");
+
+			if (py_matrix2)
+				delete(py_matrix2);
 		}
 		else
@@ -258,4 +294,5 @@
 	long* lmatrix=NULL;
 	int i;
+	PyObject* py_matrix2=NULL;
 
 	if     (PyArray_Check((PyArrayObject*)py_matrix)) {
@@ -274,4 +311,9 @@
 
 		if (M && N) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_matrix)) {
+				py_matrix2=PyArray_ContiguousFromAny(py_matrix,NPY_BOOL,ndim,ndim);
+				py_matrix=py_matrix2;
+			}
+
 			if      (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_DOUBLE) {
 				/*retrieve internal value: */
@@ -283,5 +325,5 @@
 			}
 
-			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_INT64) {
+			else if (PyArray_TYPE((PyArrayObject*)py_matrix) == NPY_LONG) {
 				/*retrieve internal value: */
 				lmatrix=(long*)PyArray_DATA((PyArrayObject*)py_matrix);
@@ -303,4 +345,7 @@
 			else
 				_error_("unrecognized bool pyarray type in input!");
+
+			if (py_matrix2)
+				delete(py_matrix2);
 		}
 		else
@@ -335,4 +380,5 @@
 	bool* bvector=NULL;
 	int i;
+	PyObject* py_vector2=NULL;
 
 	if     (PyArray_Check((PyArrayObject*)py_vector)) {
@@ -354,4 +400,9 @@
 
 		if (M) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_vector)) {
+				py_vector2=PyArray_ContiguousFromAny(py_vector,NPY_DOUBLE,ndim,ndim);
+				py_vector=py_vector2;
+			}
+
 			if      (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_DOUBLE) {
 				/*retrieve internal value: */
@@ -363,5 +414,5 @@
 			}
 
-			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_INT64) {
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_LONG) {
 				/*retrieve internal value: */
 				lvector=(long*)PyArray_DATA((PyArrayObject*)py_vector);
@@ -383,4 +434,7 @@
 			else
 				_error_("unrecognized double pyarray type in input!");
+
+			if (py_vector2)
+				delete(py_vector2);
 		}
 		else
@@ -413,4 +467,5 @@
 	double* dvector=NULL;
 	int i;
+	PyObject* py_vector2=NULL;
 
 	if     (PyArray_Check((PyArrayObject*)py_vector)) {
@@ -432,4 +487,9 @@
 
 		if (M) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_vector)) {
+				py_vector2=PyArray_ContiguousFromAny(py_vector,NPY_LONG,ndim,ndim);
+				py_vector=py_vector2;
+			}
+
 			if      (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_DOUBLE) {
 				/*retrieve internal value: */
@@ -441,5 +501,5 @@
 			}
 
-			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_INT64) {
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_LONG) {
 				/*retrieve internal value: */
 				lvector=(long*)PyArray_DATA((PyArrayObject*)py_vector);
@@ -461,4 +521,7 @@
 			else
 			 _error_("unrecognized int pyarray type in input!");
+
+			if (py_vector2)
+				delete(py_vector2);
 		}
 		else
@@ -491,4 +554,5 @@
 	long* lvector=NULL;
 	int i;
+	PyObject* py_vector2=NULL;
 
 	if     (PyArray_Check((PyArrayObject*)py_vector)) {
@@ -510,4 +574,9 @@
 
 		if (M) {
+			if (!PyArray_ISCONTIGUOUS((PyArrayObject*)py_vector)) {
+				py_vector2=PyArray_ContiguousFromAny(py_vector,NPY_BOOL,ndim,ndim);
+				py_vector=py_vector2;
+			}
+
 			if      (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_DOUBLE) {
 				/*retrieve internal value: */
@@ -519,5 +588,5 @@
 			}
 
-			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_INT64) {
+			else if (PyArray_TYPE((PyArrayObject*)py_vector) == NPY_LONG) {
 				/*retrieve internal value: */
 				lvector=(long*)PyArray_DATA((PyArrayObject*)py_vector);
@@ -539,4 +608,7 @@
 			else
 				_error_("unrecognized bool pyarray type in input!");
+
+			if (py_vector2)
+				delete(py_vector2);
 		}
 		else
@@ -656,5 +728,5 @@
 		if(i+1 == nrhs) _error_("Argument " << i+2 << " must exist and be value of option \"" << name << "\".");
 
-		_pprintLine_("FetchData for Options not implemented yet, ignoring option \"" << name << "\"!");
+		_printf0_("FetchData for Options not implemented yet, ignoring option \"" << name << "\"!\n");
 
 //		option=(Option*)OptionParse(name,&PyTuple_GetItem(py_tuple,(Py_ssize_t)(i+1)));
@@ -667,10 +739,10 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(DataSet** pcontours,PyObject* py_list){{{*/
-void FetchData(DataSet** pcontours,PyObject* py_list){
+/*FUNCTION FetchData(Contours** pcontours,PyObject* py_list){{{*/
+void FetchData(Contours** pcontours,PyObject* py_list){
 
 	int              numcontours,test1,test2;
 	char            *contourname = NULL;
-	DataSet         *contours    = NULL;
+	Contours         *contours    = NULL;
 	Contour<double> *contouri    = NULL;
 	PyObject        *py_dicti    = NULL;
@@ -679,14 +751,14 @@
 	if (PyString_Check(py_list)){
 		FetchData(&contourname,py_list);
-		contours=DomainOutlineRead<double>(contourname);
+		contours=ExpRead<double>(contourname);
 	}
 	else if(PyList_Check(py_list)){
 
-		contours=new DataSet(0);
+		contours=new Contours();
 		numcontours=(int)PyList_Size(py_list);
 
 		for(int i=0;i<numcontours;i++){
 
-			contouri=xNew<Contour<double> >(1);
+			contouri=new Contour<double>();
 			py_dicti=PyList_GetItem(py_list,(Py_ssize_t)i);
 
Index: /issm/trunk/src/wrappers/python/io/WritePythonData.cpp
===================================================================
--- /issm/trunk/src/wrappers/python/io/WritePythonData.cpp	(revision 15395)
+++ /issm/trunk/src/wrappers/python/io/WritePythonData.cpp	(revision 15396)
@@ -13,8 +13,6 @@
 
 #include "./pythonio.h"
-#include "../../c/include/include.h"
-#include "../../c/Container/Container.h"
 #include "../../c/shared/shared.h"
-#include "../../c/EnumDefinitions/EnumDefinitions.h"
+#include "../../c/shared/Enum/Enum.h"
 
 /*Primitive data types*/
@@ -74,4 +72,38 @@
 
 	PyTuple_SetItem(tuple, index, array);
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index, double* vector, int M){{{*/
+void WriteData(PyObject* py_tuple, int index, double* vector, int M){
+
+	double   *buffer = NULL;
+	npy_intp  dim   = 10;
+	PyObject *array = NULL;
+
+	/*Copy vector*/
+	buffer=xNew<double>(M);
+	for(int i=0;i<M;i++)buffer[i]=vector[i];
+
+	dim=(npy_intp)M;
+	array=PyArray_SimpleNewFromData(1,&dim,NPY_DOUBLE,buffer);
+
+	PyTuple_SetItem(py_tuple, index, array);
+
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index, int* vector, int M){{{*/
+void WriteData(PyObject* py_tuple, int index, int* vector, int M){
+
+	long* lvector=NULL;
+	npy_intp dim=10;
+	PyObject* array=NULL;
+
+	/*transform into long matrix: */
+	lvector=xNew<long>(M);
+	for(int i=0;i<M;i++)lvector[i]=(long)vector[i];
+
+	dim=(npy_intp)M;
+	array=PyArray_SimpleNewFromData(1,&dim,NPY_INT64,lvector);
+
+	PyTuple_SetItem(py_tuple, index, array);
+
 }/*}}}*/
 /*FUNCTION WriteData(PyObject* py_tuple,int index){{{*/
@@ -129,6 +161,6 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(PyObject* py_tuple,int index,SeqMat<double>* matrix){{{*/
-void WriteData(PyObject* py_tuple,int index,SeqMat<double>* matrix){
+/*FUNCTION WriteData(PyObject* py_tuple,int index,IssmDenseMat<double>* matrix){{{*/
+void WriteData(PyObject* py_tuple,int index,IssmDenseMat<double>* matrix){
 
 	int M,N;
@@ -147,6 +179,6 @@
 
 }/*}}}*/
-/*FUNCTION WriteData(PyObject* py_tuple,int index,SeqVec<double>* vector){{{*/
-void WriteData(PyObject* py_tuple,int index,SeqVec<double>* vector){
+/*FUNCTION WriteData(PyObject* py_tuple,int index,IssmSeqVec<double>* vector){{{*/
+void WriteData(PyObject* py_tuple,int index,IssmSeqVec<double>* vector){
 
 	int M;
@@ -160,84 +192,4 @@
 	dim=(npy_intp)M;
 	array=PyArray_SimpleNewFromData(1,&dim,NPY_DOUBLE,buffer);
-
-	PyTuple_SetItem(py_tuple, index, array);
-}
-/*}}}*/
-/*FUNCTION WriteData(PyObject* py_tuple,int index,SeqMat<int>* matrix){{{*/
-void WriteData(PyObject* py_tuple,int index,SeqMat<int>* matrix){
-
-	int M,N;
-	int* ibuffer=NULL;
-	npy_intp dims[2]={0,0};
-	PyObject* array=NULL;
-
-	matrix->GetSize(&M,&N);
-	ibuffer=matrix->ToSerial();
-
-	/*convert to long*/
-	long* lbuffer=xNew<long>(M*N);
-	for(int i=0;i<M*N;i++) lbuffer[i]=(long)ibuffer[i];
-	xDelete<int>(ibuffer);
-
-	dims[0]=(npy_intp)M;
-	dims[1]=(npy_intp)N;
-	array=PyArray_SimpleNewFromData(2,dims,NPY_INT64,lbuffer);
-
-	PyTuple_SetItem(py_tuple, index, array);
-
-}/*}}}*/
-/*FUNCTION WriteData(PyObject* py_tuple,int index,SeqVec<int>* vector){{{*/
-void WriteData(PyObject* py_tuple,int index,SeqVec<int>* vector){
-
-	int M;
-	int* ibuffer=NULL;
-	npy_intp dim=10;
-	PyObject* array=NULL;
-
-	vector->GetSize(&M);
-	ibuffer=vector->ToMPISerial();
-
-	/*convert to long*/
-	long* lbuffer=xNew<long>(M);
-	for(int i=0;i<M;i++) lbuffer[i]=(long)ibuffer[i];
-	xDelete<int>(ibuffer);
-
-	dim=(npy_intp)M;
-	array=PyArray_SimpleNewFromData(1,&dim,NPY_INT64,lbuffer);
-
-	PyTuple_SetItem(py_tuple, index, array);
-}
-/*}}}*/
-/*FUNCTION WriteData(PyObject* py_tuple,int index,SeqMat<bool>* matrix){{{*/
-void WriteData(PyObject* py_tuple,int index,SeqMat<bool>* matrix){
-
-	int M,N;
-	bool* buffer=NULL;
-	npy_intp dims[2]={0,0};
-	PyObject* array=NULL;
-
-	matrix->GetSize(&M,&N);
-	buffer=matrix->ToSerial();
-
-	dims[0]=(npy_intp)M;
-	dims[1]=(npy_intp)N;
-	array=PyArray_SimpleNewFromData(2,dims,NPY_BOOL,buffer);
-
-	PyTuple_SetItem(py_tuple, index, array);
-
-}/*}}}*/
-/*FUNCTION WriteData(PyObject* py_tuple,int index,SeqVec<bool>* vector){{{*/
-void WriteData(PyObject* py_tuple,int index,SeqVec<bool>* vector){
-
-	int M;
-	bool* buffer=NULL;
-	npy_intp dim=10;
-	PyObject* array=NULL;
-
-	vector->GetSize(&M);
-	buffer=vector->ToMPISerial();
-
-	dim=(npy_intp)M;
-	array=PyArray_SimpleNewFromData(1,&dim,NPY_BOOL,buffer);
 
 	PyTuple_SetItem(py_tuple, index, array);
Index: /issm/trunk/src/wrappers/python/io/pythonio.h
===================================================================
--- /issm/trunk/src/wrappers/python/io/pythonio.h	(revision 15395)
+++ /issm/trunk/src/wrappers/python/io/pythonio.h	(revision 15396)
@@ -13,7 +13,7 @@
 
 #include "../include/pythonincludes.h"
+#include "../../c/bamg/bamgobjects.h"
 #include "../../c/classes/classes.h"
-#include "../../c/Container/Container.h"
-#include "../../c/include/include.h"
+#include "../../c/shared/shared.h"
 
 void WriteData(PyObject* py_tuple,int index, double* matrix, int M,int N);
@@ -21,12 +21,10 @@
 void WriteData(PyObject* py_tuple,int index, bool* matrix, int M,int N);
 void WriteData(PyObject* py_tuple,int index, int integer);
+void WriteData(PyObject* py_tuple,int index, double* vector, int M);
+void WriteData(PyObject* py_tuple,int index, int* vector, int M);
 void WriteData(PyObject* py_tuple,int index, char* string);
 void WriteData(PyObject* py_tuple,int index);
-void WriteData(PyObject* py_tuple,int index, SeqMat<double>* matrix);
-void WriteData(PyObject* py_tuple,int index, SeqVec<double>* vector);
-void WriteData(PyObject* py_tuple,int index, SeqMat<int>* matrix);
-void WriteData(PyObject* py_tuple,int index, SeqVec<int>* vector);
-void WriteData(PyObject* py_tuple,int index, SeqMat<bool>* matrix);
-void WriteData(PyObject* py_tuple,int index, SeqVec<bool>* vector);
+void WriteData(PyObject* py_tuple,int index, IssmDenseMat<double>* matrix);
+void WriteData(PyObject* py_tuple,int index, IssmSeqVec<double>* vector);
 void WriteData(PyObject* py_tuple,int index, BamgGeom* bamggeom);
 void WriteData(PyObject* py_tuple,int index, BamgMesh* bamgmesh);
@@ -47,5 +45,5 @@
 void FetchData(BamgOpts** bamgopts,PyObject* py_dict);
 void FetchData(Options** poptions,int istart, int nrhs,PyObject* py_tuple);
-void FetchData(DataSet** pcontours,PyObject* py_list);
+void FetchData(Contours** pcontours,PyObject* py_list);
 
 int CheckNumPythonArguments(PyObject* inputs,int NRHS, void (*function)( void ));
@@ -57,3 +55,6 @@
 PyObject* PyArrayFromCopiedData(int dimi,int dimj,bool* data);
 
+/*Print*/
+void ApiPrintf(const char* string);
+
 #endif	/* _IO_H_ */
Index: /issm/trunk/test/NightlyRun/IdToName.m
===================================================================
--- /issm/trunk/test/NightlyRun/IdToName.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/IdToName.m	(revision 15396)
@@ -97,4 +97,7 @@
 	case 328, name='SquareSheetConstrainedSmbGradients2d';
 	case 329, name='SquareSheetConstrainedSmbGradients3d';
+	case 331, name='SquareSheetConstrainedHydrologyShreve';
+	case 332, name='SquareSheetConstrainedHydrologyDC';
+	case 333, name='SquareSheetHydrologyDCTwoLayers';
 	case 401, name='SquareSheetShelfDiagM2d';
 	case 402, name='SquareSheetShelfDiagM3d';
@@ -129,4 +132,5 @@
 	case 431, name='SquareSheetShelfSteaEnthalpyM3d';
 	case 432, name='SquareSheetShelfSteaEnthalpyP3d';
+	case 433, name='RoundSheetShelfGLMigrationM3d';
 	case 501, name='PigDiagM2d';
 	case 502, name='PigDiagP3d';
@@ -186,4 +190,17 @@
 	case 1601, name='SquareShelfM2dRotation';
 	case 1602, name='SquareSheetShelfP3dRotation';
+	case 2001, name='SquareSheetConstrainedGia2d';
+	case 2051, name='GiaBenchmarksAB2dA1';
+	case 2052, name='GiaBenchmarksAB2dA2';
+	case 2053, name='GiaBenchmarksAB2dA3';
+	case 2061, name='GiaBenchmarksAB2dB1';
+	case 2062, name='GiaBenchmarksAB2dB2';
+	case 2063, name='GiaBenchmarksAB2dB3';
+	case 2071, name='GiaBenchmarksAB2dC1';
+	case 2072, name='GiaBenchmarksAB2dC2';
+	case 2073, name='GiaBenchmarksAB2dC3';
+	case 2081, name='GiaBenchmarksAB2dD1';
+	case 2082, name='GiaBenchmarksAB2dD2';
+	case 2083, name='GiaBenchmarksAB2dD3';
 	case 3001, name='SquareShelfConstrainedDiagM2dAdolc';
 	case 3002, name='SquareShelfConstrainedDiagM3dAdolc';
@@ -196,4 +213,6 @@
 	case 3009, name='SquareShelfConstrainedTherTranAdolc';
 	case 3010, name='SquareShelfConstrainedTranM2dAdolc';
+	case 3015, name='SquareShelfConstrainedProg2dAdolcForwardDifference';
+	case 3019, name='SquareShelfConstrainedTherTranAdolcReverseVsForward';
 
 	otherwise, name='N/A';
Index: /issm/trunk/test/NightlyRun/IdToName.py
===================================================================
--- /issm/trunk/test/NightlyRun/IdToName.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/IdToName.py	(revision 15396)
@@ -98,4 +98,6 @@
 		328 : 'SquareSheetConstrainedSmbGradients2d',
 		329 : 'SquareSheetConstrainedSmbGradients3d',
+		331 : 'SquareSheetConstrainedHydrology',
+		333 : 'SquareSheetConstrainedTranCflM3d',
 		401 : 'SquareSheetShelfDiagM2d',
 		402 : 'SquareSheetShelfDiagM3d',
@@ -126,8 +128,9 @@
 		427 : 'SquareSheetShelfGroundingLine3dSoft',
 		428 : 'SquareSheetShelfDiagM2dNewton',
-		439 : 'SquareSheetShelfDiagP3dNewton',
+		429 : 'SquareSheetShelfDiagP3dNewton',
 		430 : 'SquareSheetShelfDiagS3dNewton',
 		431 : 'SquareSheetShelfSteaEnthalpyM3d',
 		432 : 'SquareSheetShelfSteaEnthalpyP3d',
+		433 : 'RoundSheetShelfGLMigrationM3d',
 		501 : 'PigDiagM2d',
 		502 : 'PigDiagP3d',
@@ -187,4 +190,5 @@
 		1601 : 'SquareShelfM2dRotation',
 		1602 : 'SquareSheetShelfP3dRotation', 
+		2001 : 'SquareSheetConstrainedGia2d',
 		3001 : 'SquareShelfConstrainedDiagM2dAdolc',
 		3002 : 'SquareShelfConstrainedDiagM3dAdolc',
@@ -197,4 +201,6 @@
 		3009 : 'SquareShelfConstrainedTherTranAdolc',
 		3010 : 'SquareShelfConstrainedTranM2dAdolc',
+		3015 : 'SquareShelfConstrainedProg2dAdolcForwardDifference',
+		3019 : 'SquareShelfConstrainedTherTranAdolcReverseVsForward',
 	}
 
Index: /issm/trunk/test/NightlyRun/Makefile
===================================================================
--- /issm/trunk/test/NightlyRun/Makefile	(revision 15395)
+++ /issm/trunk/test/NightlyRun/Makefile	(revision 15396)
@@ -1,2 +1,2 @@
 clean: 
-	rm -rf *.tar.gz *.bin *.errlog *.outlog  *.outbin *.petsc *.queue *.run valgrind.log* *.bat *.lock qmu*
+	rm -rf *.tar.gz *.bin *.errlog *.outlog  *.outbin *.petsc *.queue *.toolkits *.run valgrind.log* *.bat *.lock qmu*
Index: /issm/trunk/test/NightlyRun/android.m
===================================================================
--- /issm/trunk/test/NightlyRun/android.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/android.m	(revision 15396)
@@ -1,3 +1,3 @@
-md=triangle(model(),'../Exp/Square.exp',100000.);
+md=triangle(model(),'../Exp/Square.exp',40000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
Index: /issm/trunk/test/NightlyRun/runme.m
===================================================================
--- /issm/trunk/test/NightlyRun/runme.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/runme.m	(revision 15396)
@@ -12,5 +12,6 @@
 %      'id'            followed by the list of ids requested
 %      'exclude'       ids to be excluded from the test
-%      'benchmark'     'nightly' (nightly run/ daily run)
+%      'benchmark'     'all' (all of them)
+%                      'nightly' (nightly run/ daily run)
 %                      'ismip'  : validation of ismip-hom tests
 %                      'eismint': validation of eismint tests
@@ -18,16 +19,16 @@
 %                      'mesh'   : validation of mesh tests
 %                      'adolc'   : validation of adolc tests
+%                      'gia'   : validation of gia tests
 %                      ...
 %      'procedure'     'check' : run the test (default)
 %                      'update': update the archive
-%                      'model' : prepare the model but no test is run
 %
 %   Usage:
-%      md=runme(varargin);
+%      runme(varargin);
 %
 %   Examples:
 %      runme;
 %      runme('exclude',101);
-%      md=runme('id',102,'procedure','model');
+%      runme('id',102,'procedure','update');
 
 %Get ISSM_DIR variable
@@ -48,5 +49,5 @@
 %GET benchmark {{{
 benchmark=getfieldvalue(options,'benchmark','nightly');
-if ~ismember(benchmark,{'all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing','adolc'})
+if ~ismember(benchmark,{'all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing','adolc','gia'})
 	disp('runme warning: benchmark not supported, defaulting to test ''nightly''')
 	benchmark='nightly';
@@ -116,4 +117,6 @@
 elseif strcmpi(benchmark,'referential'),
 	test_ids=intersect(test_ids,[1601:1602]);
+elseif strcmpi(benchmark,'gia'),
+	test_ids=intersect(test_ids,[2001:2100]);
 elseif strcmpi(benchmark,'adolc'),
 	test_ids=intersect(test_ids,[3001:3020]);
@@ -217,7 +220,2 @@
 	end
 end
-
-%output md if requested
-if nargout==1
-	varargout{1}=md;
-end
Index: /issm/trunk/test/NightlyRun/runme.py
===================================================================
--- /issm/trunk/test/NightlyRun/runme.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/runme.py	(revision 15396)
@@ -22,9 +22,13 @@
 	       'id'            followed by the list of ids requested
 	       'exclude'       ids to be excluded from the test
-	       'benchmark'     'nightly' (nightly run/ daily run)
+	       'benchmark'     'all' (all of the tests)
+		                   'nightly' (nightly run/ daily run)
 	                       'ismip'  : validation of ismip-hom tests
 	                       'eismint': validation of eismint tests
 	                       'thermal': validation of thermal tests
 	                       'mesh'   : validation of mesh tests
+						   'adolc'   : validation of adolc tests
+                           'gia'   : validation of gia tests
+
 	                       ...
 	       'procedure'     'check' : run the test (default)
@@ -32,10 +36,10 @@
  
 	    Usage:
-	       md=runme(varargin);
+	       runme(varargin);
  
 	    Examples:
 	       runme()
 	       runme(exclude=101)
-	       md=runme(id=102,procedure='update')
+	       runme(id=102,procedure='update')
 	"""
 
@@ -50,5 +54,5 @@
 	#Process options
 	#GET benchmark {{{
-	if not ismember(benchmark,['all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing','adolc']):
+	if not ismember(benchmark,['all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing','adolc','gia']):
 		print "runme warning: benchmark '%s' not supported, defaulting to test 'nightly'." % benchmark
 		benchmark='nightly'
@@ -113,4 +117,6 @@
 	elif strcmpi(benchmark,'referential'):
 		test_ids=test_ids.intersection(set(range(1601,1603)))
+	elif strcmpi(benchmark,'gia'):
+		test_ids=test_ids.intersection(set(range(2001,2100)))
 	elif strcmpi(benchmark,'adolc'):
 		test_ids=test_ids.intersection(set(range(3001,3020)))
@@ -144,4 +150,6 @@
 						else:
 							field=field.reshape(0,0)
+					elif len(field.shape) == 0:
+						field=field.reshape(1,1)
 					# Matlab uses base 1, so use base 1 in labels
 					f.createDimension(archive_name+'_field'+str(k+1)+'_1',numpy.size(field,0))
@@ -234,9 +242,4 @@
 				raise RuntimeError(me)
 
-#	#output md if requested
-#	if nargout==1
-#		varargout{1}=md;
-#	end
-
 	return
 
Index: /issm/trunk/test/NightlyRun/test111.m
===================================================================
--- /issm/trunk/test/NightlyRun/test111.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test111.m	(revision 15396)
@@ -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-13,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,2e-11,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-11};
+	1e-09,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,2e-11,...
+	1e-09,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-11};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test111.py
===================================================================
--- /issm/trunk/test/NightlyRun/test111.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test111.py	(revision 15396)
@@ -24,6 +24,6 @@
 field_tolerances=[\
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-13,\
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,2e-11,\
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-11]
+	1e-09,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,2e-11,\
+	1e-09,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-11]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test1110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1110.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test1110.m	(revision 15396)
@@ -54,5 +54,5 @@
 	md.prognostic.stabilization=1;
 	md.diagnostic.maxiter=1;
-
+	
 	%Compute the diagnostic
 	md.cluster=generic('name',oshostname(),'np',8);
Index: /issm/trunk/test/NightlyRun/test119.m
===================================================================
--- /issm/trunk/test/NightlyRun/test119.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test119.m	(revision 15396)
@@ -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.7};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,0.8};
 field_values={...
 	x1, y1,...
Index: /issm/trunk/test/NightlyRun/test119.py
===================================================================
--- /issm/trunk/test/NightlyRun/test119.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test119.py	(revision 15396)
@@ -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.7]
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,0.8]
 field_values=[\
 	x1, y1,\
Index: /issm/trunk/test/NightlyRun/test2001.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2001.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2001.m	(revision 15396)
@@ -0,0 +1,29 @@
+%GIA test, inspired on test101
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=2400000; %2,400 kyr :: EVALUATION TIME
+% to get rid of default final_time: make sure final_time>start_time
+md.timestepping.final_time=2500000; %2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness; 0.0],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/trunk/test/NightlyRun/test2001.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2001.py	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2001.py	(revision 15396)
@@ -0,0 +1,44 @@
+import numpy
+import copy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+#Define a model 
+md=model()
+md=triangle(md,'../Exp/Square.exp',100000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+
+#Indicate what you want to compute 
+md.gia.cross_section_shape=1    # for square-edged x-section 
+
+#Define loading history (see test2001.m for the description)
+md.timestepping.start_time=2400000 # 2,400 kyr
+md.timestepping.final_time=2500000 # 2,500 kyr
+md.geometry.thickness=[\
+	[md.geometry.thickness*0.0; 0.0],\
+	[md.geometry.thickness/2.0; 0.1],\
+	[md.geometry.thickness; 0.2],\
+	[md.geometry.thickness; 1.0],\
+	[md.geometry.thickness; md.timestepping.start_time],\
+	]
+
+#Solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3)
+md.verbose=verbose('1111111')
+md=solve(md,GiaSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['GiaW','GiadWdt']
+field_tolerances=[1e-13,1e-13]
+field_values    =[\
+		md.results.GiaSolution.GiaW,\
+		md.results.GiaSolution.GiadWdt,\
+		]
+
Index: /issm/trunk/test/NightlyRun/test2051.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2051.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2051.m	(revision 15396)
@@ -0,0 +1,31 @@
+% Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksAB.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=2002100; % after 2 kyr of deglaciation 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness; 1000],...
+	[md.geometry.thickness; 2000000],...
+	[md.geometry.thickness*0.0; 2000100],...
+	[md.geometry.thickness*0.0; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/trunk/test/NightlyRun/test2052.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2052.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2052.m	(revision 15396)
@@ -0,0 +1,31 @@
+% Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksAB.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=2005100; % after 5 kyr of deglaciation 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness; 1000],...
+	[md.geometry.thickness; 2000000],...
+	[md.geometry.thickness*0.0; 2000100],...
+	[md.geometry.thickness*0.0; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/trunk/test/NightlyRun/test2053.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2053.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2053.m	(revision 15396)
@@ -0,0 +1,31 @@
+% Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksAB.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=2010100; % after 10 kyr of deglaciation 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness; 1000],...
+	[md.geometry.thickness; 2000000],...
+	[md.geometry.thickness*0.0; 2000100],...
+	[md.geometry.thickness*0.0; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/trunk/test/NightlyRun/test2071.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2071.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2071.m	(revision 15396)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=0.3;     % for t \approx 0 kyr : to get eleastic response!   
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/trunk/test/NightlyRun/test2072.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2072.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2072.m	(revision 15396)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=1000.3;  % for t \approx 1 kyr 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/trunk/test/NightlyRun/test2073.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2073.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2073.m	(revision 15396)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=1;    % for square-edged x-section 
+
+%% define loading history 
+md.timestepping.start_time=2400000; % for t \approx \infty 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/trunk/test/NightlyRun/test2081.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2081.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2081.m	(revision 15396)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2d Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=2;    % for elliptical edge  
+
+%% define loading history 
+md.timestepping.start_time=0.3;     % for t \approx 0 kyr : to get eleastic response!   
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/trunk/test/NightlyRun/test2082.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2082.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2082.m	(revision 15396)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2d Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=2;    % for elliptical edge 
+
+%% define loading history 
+md.timestepping.start_time=1000.3;  % for t \approx 1 kyr 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/trunk/test/NightlyRun/test2083.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2083.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test2083.m	(revision 15396)
@@ -0,0 +1,30 @@
+% Benchmark experiments (Figure A2d Ivins and James, 1999, Geophys. J. Int.) 
+md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/GiaBenchmarksCD.par');
+
+%% indicate what you want to compute 
+md.gia.cross_section_shape=2;    % for elliptical edge 
+
+%% define loading history 
+md.timestepping.start_time=2400000; % for t \approx \infty 
+md.timestepping.final_time=2500000; % 2,500 kyr
+md.geometry.thickness=[...
+	[md.geometry.thickness*0.0; 0.0],...
+	[md.geometry.thickness/2.0; 0.1],...
+	[md.geometry.thickness; 0.2],...
+	[md.geometry.thickness; md.timestepping.start_time],...
+	];
+
+%% solve for GIA deflection 
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('1111111');
+md=solve(md,GiaSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'GiaW','GiadWdt'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.GiaSolution.GiaW),...
+	(md.results.GiaSolution.GiadWdt),...
+	};
Index: /issm/trunk/test/NightlyRun/test234.m
===================================================================
--- /issm/trunk/test/NightlyRun/test234.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test234.m	(revision 15396)
@@ -42,5 +42,6 @@
 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');
-if (str2num(dakotaversion())>4.2)
+dver=textscan(dakotaversion(),'%[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')
 end
@@ -52,4 +53,5 @@
 md.qmu.params.evaluation_concurrency=1;
 md.qmu.params.interval_type='forward';
+md.qmu.params.tabular_graphics_data=true;
 md.qmu.isdakota=1;
 
Index: /issm/trunk/test/NightlyRun/test3001.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3001.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3001.m	(revision 15396)
@@ -3,7 +3,9 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
+md.toolkits.DefaultAnalysis=issmsolver();
 md.diagnostic.requested_outputs=StressTensorEnum();
 md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,DiagnosticSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3001.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3001.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3001.py	(revision 15396)
@@ -12,6 +12,7 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md=setflowequation(md,'macayeal','all')
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
 md.diagnostic.requested_outputs=StressTensorEnum()
+md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
 md=solve(md,DiagnosticSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3002.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3002.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3002.m	(revision 15396)
@@ -4,6 +4,7 @@
 md=extrude(md,3,2.);
 md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,DiagnosticSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3002.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3002.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3002.py	(revision 15396)
@@ -13,6 +13,7 @@
 md.extrude(3,2.)
 md=setflowequation(md,'macayeal','all')
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
 md.autodiff.isautodiff=True
+md.toolkits.DefaultAnalysis=issmsolver()
 md=solve(md,DiagnosticSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test3003.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3003.m	(revision 15396)
@@ -4,7 +4,8 @@
 md=extrude(md,3,2.);
 md=setflowequation(md,'pattyn','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.diagnostic.requested_outputs=StressTensorEnum();
 md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,DiagnosticSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3003.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3003.py	(revision 15396)
@@ -13,6 +13,7 @@
 md.extrude(3,2.)
 md=setflowequation(md,'pattyn','all')
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
 md.diagnostic.requested_outputs=StressTensorEnum()
+md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
 md=solve(md,DiagnosticSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3004.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3004.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3004.m	(revision 15396)
@@ -4,6 +4,7 @@
 md=extrude(md,3,2.);
 md=setflowequation(md,'stokes','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,DiagnosticSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3004.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3004.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3004.py	(revision 15396)
@@ -13,5 +13,6 @@
 md.extrude(3,2.)
 md=setflowequation(md,'stokes','all')
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
+md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
 md=solve(md,DiagnosticSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3005.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3005.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3005.m	(revision 15396)
@@ -3,6 +3,7 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,PrognosticSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3005.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3005.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3005.py	(revision 15396)
@@ -12,5 +12,6 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md=setflowequation(md,'macayeal','all')
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
+md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
 md=solve(md,PrognosticSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3006.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3006.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3006.m	(revision 15396)
@@ -4,8 +4,9 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.prognostic.stabilization=3;
 md.prognostic.spcthickness=md.geometry.thickness;
 md.autodiff.isautodiff=true;
+md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
 md=solve(md,PrognosticSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test3006.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3006.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3006.py	(revision 15396)
@@ -14,7 +14,8 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md=setflowequation(md,'macayeal','all')
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
 md.prognostic.stabilization=3
 md.prognostic.spcthickness=md.geometry.thickness
+md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
 md=solve(md,PrognosticSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3007.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3007.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3007.m	(revision 15396)
@@ -4,7 +4,8 @@
 md=setflowequation(md,'macayeal','all');
 md=extrude(md,5,3.);
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
 md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmsolver();
 md=solve(md,PrognosticSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test3007.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3007.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3007.py	(revision 15396)
@@ -13,5 +13,6 @@
 md=setflowequation(md,'macayeal','all')
 md.extrude(5,3.)
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
+md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
 md=solve(md,PrognosticSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3008.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3008.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3008.m	(revision 15396)
@@ -5,7 +5,8 @@
 md=setflowequation(md,'macayeal','all');
 md.timestepping.time_step=0;
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
 md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmsolver();
 md=solve(md,ThermalSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test3008.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3008.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3008.py	(revision 15396)
@@ -14,5 +14,6 @@
 md=setflowequation(md,'macayeal','all')
 md.timestepping.time_step=0
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
+md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
 md=solve(md,ThermalSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3009.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3009.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3009.m	(revision 15396)
@@ -4,5 +4,5 @@
 md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.transient.isdiagnostic=0;
 md.transient.isprognostic=0;
@@ -11,4 +11,5 @@
 md.autodiff.isautodiff=true;
 md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmsolver();
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test3009.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3009.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3009.py	(revision 15396)
@@ -13,9 +13,10 @@
 md.extrude(3,1.)
 md=setflowequation(md,'macayeal','all')
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
 md.transient.isdiagnostic=False
 md.transient.isprognostic=False
 md.transient.isthermal=True
 md.transient.isgroundingline=False
+md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test3010.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3010.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3010.m	(revision 15396)
@@ -3,9 +3,10 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.transient.requested_outputs=IceVolumeEnum();
 
 md.autodiff.isautodiff=true;
 md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmsolver();
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test3010.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3010.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3010.py	(revision 15396)
@@ -12,5 +12,6 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md=setflowequation(md,'macayeal','all')
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
+md.toolkits.DefaultAnalysis=issmsolver()
 md.transient.requested_outputs=IceVolumeEnum()
 
Index: /issm/trunk/test/NightlyRun/test3015.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3015.m	(revision 15396)
@@ -7,7 +7,8 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.prognostic.requested_outputs=IceVolumeEnum();
 md.verbose=verbose('autodiff',true);
+md.toolkits.DefaultAnalysis=issmsolver();
 
 %setup autodiff parameters
Index: /issm/trunk/test/NightlyRun/test3019.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3019.m	(revision 15396)
@@ -4,5 +4,6 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
+md.toolkits.DefaultAnalysis=issmsolver();
 
 md.autodiff.isautodiff=true;
@@ -31,4 +32,4 @@
 %Fields and tolerances to track changes
 field_names     ={'Jac Forward','Jac Reverse','Jac Forward - Reverse'};
-field_tolerances={1e-13,1e-13,1e-13};
+field_tolerances={1e-8,1e-8,1e-6};
 field_values={jac_forward,jac_reverse,jac_forward-jac_reverse};
Index: /issm/trunk/test/NightlyRun/test3020.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3020.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3020.m	(revision 15396)
@@ -7,8 +7,9 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1);
 md.transient.requested_outputs=[IceVolumeEnum();MaxVelEnum()];
 md.verbose=verbose('autodiff',true);
-md.diagnostic.restol=0.000001;
+md.diagnostic.restol=1e-4;
+md.toolkits.DefaultAnalysis=issmsolver();
 
 %setup autodiff parameters
@@ -81,4 +82,4 @@
 %Fields and tolerances to track changes
 field_names     ={'dV/dh-dV/dh0','dMaxV/dh-dMaxV/dh0'};
-field_tolerances={1e-13,1e-13};
+field_tolerances={1e-8,1e-7};
 field_values={dVdh_ad-dVdh_an,dMaxVdh_an-dMaxVdh_ad};
Index: /issm/trunk/test/NightlyRun/test3020.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3020.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test3020.py	(revision 15396)
@@ -21,8 +21,9 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md=setflowequation(md,'macayeal','all')
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
 md.transient.requested_outputs=[IceVolumeEnum(),MaxVelEnum()]
 md.verbose=verbose('autodiff',True)
 md.diagnostic.restol=0.000001
+md.toolkits.DefaultAnalysis=issmsolver()
 
 #setup autodiff parameters
Index: /issm/trunk/test/NightlyRun/test3021.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3021.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test3021.m	(revision 15396)
@@ -0,0 +1,25 @@
+md=triangle(model(),'../Exp/Square.exp',50000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.diagnostic.requested_outputs=StressTensorEnum();
+md.autodiff.isautodiff=false;
+md.toolkits.DefaultAnalysis=issmsolver();
+md.verbose=verbose('1111111');
+md=solve(md,DiagnosticSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure',...
+	'StressTensorxx','StressTensoryy','StressTensorxy'};
+field_tolerances={1e-13,1e-13,1e-13,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.DiagnosticSolution.StressTensorxx),...
+	(md.results.DiagnosticSolution.StressTensoryy),...
+	(md.results.DiagnosticSolution.StressTensorxy),...
+	};
Index: /issm/trunk/test/NightlyRun/test317.m
===================================================================
--- /issm/trunk/test/NightlyRun/test317.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test317.m	(revision 15396)
@@ -11,7 +11,7 @@
 	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2',...
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
-field_tolerances={1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
-	1e-09,1e-09,1e-10,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
-	1e-09,5e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,5e-10,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test317.py
===================================================================
--- /issm/trunk/test/NightlyRun/test317.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test317.py	(revision 15396)
@@ -20,7 +20,7 @@
 	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2',\
 	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
-field_tolerances=[1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
-	1e-09,1e-09,1e-10,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
-	1e-09,5e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10]
+field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		1e-09,1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,\
+		1e-09,5e-10,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test331.m
===================================================================
--- /issm/trunk/test/NightlyRun/test331.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test331.m	(revision 15396)
@@ -0,0 +1,25 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.watercolumn=10^-3*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcwatercolumn=NaN*ones(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==0);
+md.hydrology.spcwatercolumn(pos)=2*10^-3;
+md=solve(md,HydrologySolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'HydrologyWaterVx1','HydrologyWaterVy1','WaterColumn1', 'HydrologyWaterVx2','HydrologyWaterVy2','WaterColumn2', 'HydrologyWaterVx3','HydrologyWaterVy3','WaterColumn3'};
+field_tolerances={1e-09,1e-01,1e-09, 1e-09,1e-01,1e-09, 1e-09,1e-01,1e-09};
+field_values={...
+	(md.results.HydrologySolution(1).HydrologyWaterVx),...
+	(md.results.HydrologySolution(1).HydrologyWaterVy),...
+	(md.results.HydrologySolution(1).Watercolumn),...
+	(md.results.HydrologySolution(2).HydrologyWaterVx),...
+	(md.results.HydrologySolution(2).HydrologyWaterVy),...
+	(md.results.HydrologySolution(2).Watercolumn),...
+	(md.results.HydrologySolution(3).HydrologyWaterVx),...
+	(md.results.HydrologySolution(3).HydrologyWaterVy),...
+	(md.results.HydrologySolution(3).Watercolumn),...
+	};
Index: /issm/trunk/test/NightlyRun/test331.py
===================================================================
--- /issm/trunk/test/NightlyRun/test331.py	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test331.py	(revision 15396)
@@ -0,0 +1,36 @@
+import numpy
+import copy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md=setflowequation(md,'macayeal','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.initialization.watercolumn=1e-3*numpy.ones((md.mesh.numberofvertices,1))
+md.hydrology.spcwatercolumn=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+pos=numpy.nonzero(md.mesh.y==0)[0]
+md.hydrology.spcwatercolumn[pos]=2e-3
+md=solve(md,HydrologySolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['HydrologyWaterVx1','HydrologyWaterVy1','WaterColumn1','HydrologyWaterVx2','HydrologyWaterVy2','WaterColumn2','HydrologyWaterVx3','HydrologyWaterVy3','WaterColumn3']
+field_tolerances=[1e-09,1e-01,1e-09,1e-09,1e-01,1e-09,1e-09,1e-01,1e-09]
+field_values=[\
+	md.results.HydrologySolution[0].HydrologyWaterVx,\
+	md.results.HydrologySolution[0].HydrologyWaterVy,\
+	md.results.HydrologySolution[0].Watercolumn,\
+	md.results.HydrologySolution[1].HydrologyWaterVx,\
+	md.results.HydrologySolution[1].HydrologyWaterVy,\
+	md.results.HydrologySolution[1].Watercolumn,\
+	md.results.HydrologySolution[2].HydrologyWaterVx,\
+	md.results.HydrologySolution[2].HydrologyWaterVy,\
+	md.results.HydrologySolution[2].Watercolumn,\
+	]
Index: /issm/trunk/test/NightlyRun/test332.m
===================================================================
--- /issm/trunk/test/NightlyRun/test332.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test332.m	(revision 15396)
@@ -0,0 +1,27 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.hydrology=(hydrologydc);
+md.hydrology.isefficientlayer=0;
+md.hydrology.sedimentlimit_flag=1;
+md.hydrology.sedimentlimit=8000.0;
+md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==0);
+md.hydrology.spcsediment_head(pos)=0.0;
+md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.sediment_transmitivity=3;
+md.timestepping.time_step=0;
+md.timestepping.final_time=1.0;
+%md.verbose=verbose('1111111');
+md=solve(md,HydrologySolutionEnum());
+
+%Fields and tolerances to track changes
+%you can also compare with an analitic solution, but it is exact
+%only if no limits are applied
+%analitic=(md.mesh.y.^2-2*md.mesh.y*1.0e6)*(-2.0/(2*md.constants.yts*md.hydrology.sediment_transmitivity))
+field_names     ={'SedimentWaterHead','SedimentHeadResidual'};
+field_tolerances={1e-13, 1e-13};
+field_values={md.results.HydrologySolution.SedimentHead,md.results.HydrologySolution.SedimentHeadResidual}
Index: /issm/trunk/test/NightlyRun/test333.m
===================================================================
--- /issm/trunk/test/NightlyRun/test333.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test333.m	(revision 15396)
@@ -0,0 +1,62 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',1);
+md.hydrology=(hydrologydc);
+md.hydrology.isefficientlayer=1;
+md.hydrology.sedimentlimit_flag=1;
+md.hydrology.sedimentlimit=800.0;
+md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
+md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.sediment_transmitivity=3;
+
+md.initialization.epl_head=0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcepl_head=NaN*ones(md.mesh.numberofvertices,1);
+md.hydrology.mask_eplactive=0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.epl_transmitivity=30;
+md.hydrology.epl_thickness=1;
+md.timestepping.time_step=0.2;
+md.timestepping.final_time=2.0;
+
+%md.verbose.solution=1;
+
+md=solve(md,HydrologySolutionEnum());
+
+%store=md.constants.g*md.hydrology.sediment_porosity* ...
+%			md.materials.rho_freshwater*((md.hydrology.sediment_compressibility/md.hydrology.sediment_porosity)+md.hydrology.water_compressibility)
+
+%sed=ones(1,size(md.results.HydrologySolution,2));
+%epl=ones(1,size(md.results.HydrologySolution,2));
+%res=ones(1,size(md.results.HydrologySolution,2));
+%input=ones(1,size(md.results.HydrologySolution,2));
+%for i= 1:size(md.results.HydrologySolution,2)
+%	sed(i)=mean(md.results.HydrologySolution(i).SedimentHead);
+%	res(i)=mean(md.results.HydrologySolution(i).SedimentHeadResidual);
+%	epl(i)=mean(md.results.HydrologySolution(i).EplHead);
+%	input(i)=2.0*(i*0.2);
+%end
+
+%Fields and tolerances to track changes
+field_names     ={'SedimentWaterHead1','EplWaterHead1','SedimentHeadResidual1',...
+								 'SedimentWaterHead4','EplWaterHead4','SedimentHeadResidual4',...
+								 'SedimentWaterHead5','EplWaterHead5','SedimentHeadResidual5',...
+								 'SedimentWaterHead9','EplWaterHead9','SedimentHeadResidual9'};
+field_tolerances={1e-13, 1e-13, 1e-13,...
+								 1e-13, 1e-13, 1e-13,...
+								 1e-13, 1e-13, 1e-13,...
+								 1e-13, 1e-13, 1e-13};
+field_values={md.results.HydrologySolution(1).SedimentHead, ...
+							md.results.HydrologySolution(1).EplHead,...
+							md.results.HydrologySolution(1).SedimentHeadResidual,...
+							md.results.HydrologySolution(4).SedimentHead,...
+							md.results.HydrologySolution(4).EplHead,...
+							md.results.HydrologySolution(4).SedimentHeadResidual, ...
+							md.results.HydrologySolution(5).SedimentHead,...
+							md.results.HydrologySolution(5).EplHead,...
+							md.results.HydrologySolution(5).SedimentHeadResidual, ...
+							md.results.HydrologySolution(9).SedimentHead,...
+							md.results.HydrologySolution(9).EplHead,...
+							md.results.HydrologySolution(9).SedimentHeadResidual};
Index: /issm/trunk/test/NightlyRun/test405.m
===================================================================
--- /issm/trunk/test/NightlyRun/test405.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test405.m	(revision 15396)
@@ -9,5 +9,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-05,1e-05,1e-05,1e-05,1e-05};
+field_tolerances={5e-05,5e-05,5e-05,5e-05,1e-05};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test405.py
===================================================================
--- /issm/trunk/test/NightlyRun/test405.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test405.py	(revision 15396)
@@ -19,5 +19,5 @@
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-05,1e-05,1e-05,1e-05,1e-05]
+field_tolerances=[5e-05,5e-05,5e-05,5e-05,1e-05]
 field_values=[\
 	md.results.DiagnosticSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test415.m
===================================================================
--- /issm/trunk/test/NightlyRun/test415.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test415.m	(revision 15396)
@@ -24,5 +24,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-10,1e-9,1e-10,1e-13,1e-10,1e-09,1e-10,1e-8,1e-09,1e-6};
+field_tolerances={1e-10,1e-9,1e-10,1e-13,1e-09,1e-09,1e-09,1e-8,1e-09,1e-6};
 field_values={...
 	(md.results.SteadystateSolution.Gradient1),...
Index: /issm/trunk/test/NightlyRun/test415.py
===================================================================
--- /issm/trunk/test/NightlyRun/test415.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test415.py	(revision 15396)
@@ -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-9,1e-10,1e-13,1e-10,1e-09,1e-10,1e-8,1e-09,1e-6]
+field_tolerances=[1e-10,1e-9,1e-10,1e-13,1e-09,1e-09,1e-09,1e-8,1e-09,1e-6]
 field_values=[\
 	md.results.SteadystateSolution.Gradient1,\
Index: /issm/trunk/test/NightlyRun/test423.m
===================================================================
--- /issm/trunk/test/NightlyRun/test423.m	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test423.m	(revision 15396)
@@ -20,5 +20,5 @@
 md.transient.isthermal=0;
 md.transient.isprognostic=0;
-md.transient.isdiagnostic=0;
+md.transient.isdiagnostic=1;
 md.transient.isgroundingline=1;
 
@@ -27,11 +27,23 @@
 md=solve(md,TransientSolutionEnum());
 element_on_iceshelf_agressive=(md.results.TransientSolution.MaskElementonfloatingice);
+vel_agressive=(md.results.TransientSolution.Vel);
 
 md.groundingline.migration='SoftMigration';
 md=solve(md,TransientSolutionEnum());
 element_on_iceshelf_soft=(md.results.TransientSolution.MaskElementonfloatingice);
+vel_soft=(md.results.TransientSolution.Vel);
+
+md.groundingline.migration='SubelementMigration';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_subelement=(md.results.TransientSolution.GLlevelset);
+vel_subelement=(md.results.TransientSolution.Vel);
+
+md.groundingline.migration='SubelementMigration2';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_subelement2=(md.results.TransientSolution.GLlevelset);
+vel_subelement2=(md.results.TransientSolution.Vel);
 
 %Fields and tolerances to track changes
-field_names     ={'ElementOnIceShelfAgressive','ElementOnIceShelfSoft'};
-field_tolerances={1e-13,1e-13};
-field_values={element_on_iceshelf_agressive,element_on_iceshelf_soft};
+field_names     ={'ElementOnIceShelfAgressive','VelAgressive','ElementOnIceShelfSoft','VelSoft','ElementOnIceShelfSubelement','VelSubelement','ElementOnIceShelfSubelement2','VelSubelement2'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={element_on_iceshelf_agressive,vel_agressive,element_on_iceshelf_soft,vel_soft,element_on_iceshelf_subelement,vel_subelement,element_on_iceshelf_subelement2,vel_subelement2};
Index: /issm/trunk/test/NightlyRun/test423.py
===================================================================
--- /issm/trunk/test/NightlyRun/test423.py	(revision 15395)
+++ /issm/trunk/test/NightlyRun/test423.py	(revision 15396)
@@ -31,5 +31,5 @@
 md.transient.isthermal=False
 md.transient.isprognostic=False
-md.transient.isdiagnostic=False
+md.transient.isdiagnostic=True
 md.transient.isgroundingline=True
 
@@ -38,11 +38,23 @@
 md=solve(md,TransientSolutionEnum())
 element_on_iceshelf_agressive=md.results.TransientSolution[0].MaskElementonfloatingice
+vel_agressive=md.results.TransientSolution[0].Vel
 
 md.groundingline.migration='SoftMigration'
 md=solve(md,TransientSolutionEnum())
 element_on_iceshelf_soft=md.results.TransientSolution[0].MaskElementonfloatingice
+vel_soft=md.results.TransientSolution[0].Vel
+
+md.groundingline.migration='SubelementMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_subelement=md.results.TransientSolution[0].GLlevelset
+vel_subelement=md.results.TransientSolution[0].Vel
+
+md.groundingline.migration='SubelementMigration2'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_subelement2=md.results.TransientSolution[0].GLlevelset
+vel_subelement2=md.results.TransientSolution[0].Vel
 
 #Fields and tolerances to track changes
-field_names     =['ElementOnIceShelfAgressive','ElementOnIceShelfSoft']
-field_tolerances=[1e-13,1e-13]
-field_values=[element_on_iceshelf_agressive,element_on_iceshelf_soft]
+field_names     =['ElementOnIceShelfAgressive','VelAgressive','ElementOnIceShelfSoft','VelSoft','ElementOnIceShelfSubelement','VelSubelement','ElementOnIceShelfSubelement2','VelSubelement2']
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[element_on_iceshelf_agressive,vel_agressive,element_on_iceshelf_soft,vel_soft,element_on_iceshelf_subelement,vel_subelement,element_on_iceshelf_subelement2,vel_subelement2]
Index: /issm/trunk/test/NightlyRun/test433.m
===================================================================
--- /issm/trunk/test/NightlyRun/test433.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test433.m	(revision 15396)
@@ -0,0 +1,42 @@
+radius=1.e6;
+shelfextent=2.e5;
+
+md=roundmesh(model(),radius,50000.);
+%fix center node to 0,0
+rad=sqrt(md.mesh.x.^2+md.mesh.y.^2);
+pos=find(rad==min(rad));
+md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center
+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));
+flags(pos)=1;
+md=setmask(md,flags,''); 
+md=parameterize(md,'../Par/RoundSheetShelf.par');
+md=setflowequation(md,'macayeal','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.isgroundingline=1;
+
+%test different grounding line dynamics.
+md.groundingline.migration='AgressiveMigration';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_agressive=(md.results.TransientSolution.MaskElementonfloatingice);
+
+md.groundingline.migration='SoftMigration';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_soft=(md.results.TransientSolution.MaskElementonfloatingice);
+
+md.groundingline.migration='SubelementMigration';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_subelement=(md.results.TransientSolution.GLlevelset);
+
+%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};
Index: /issm/trunk/test/NightlyRun/test433.py
===================================================================
--- /issm/trunk/test/NightlyRun/test433.py	(revision 15396)
+++ /issm/trunk/test/NightlyRun/test433.py	(revision 15396)
@@ -0,0 +1,53 @@
+import numpy
+from model import *
+from roundmesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+radius=1.e6
+shelfextent=2.e5
+
+md=roundmesh(model(),radius,50000.)
+#fix center node to 0,0
+rad=numpy.sqrt(md.mesh.x**2+md.mesh.y**2)
+pos=numpy.argmin(rad)
+md.mesh.x[pos]=0.
+md.mesh.y[pos]=0.    #the closest node to the center is changed to be exactly at the center
+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))
+flags[pos]=1
+md=setmask(md,flags,'') 
+md=parameterize(md,'../Par/RoundSheetShelf.py')
+md=setflowequation(md,'macayeal','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.isgroundingline=True
+
+#test different grounding line dynamics.
+md.groundingline.migration='AgressiveMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_agressive=md.results.TransientSolution[0].MaskElementonfloatingice
+
+md.groundingline.migration='SoftMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_soft=md.results.TransientSolution[0].MaskElementonfloatingice
+
+md.groundingline.migration='SubelementMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_subelement=md.results.TransientSolution[0].GLlevelset
+
+#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]
Index: /issm/trunk/test/NightlyRun/tmp332.m
===================================================================
--- /issm/trunk/test/NightlyRun/tmp332.m	(revision 15396)
+++ /issm/trunk/test/NightlyRun/tmp332.m	(revision 15396)
@@ -0,0 +1,18 @@
+md=triangle(model(),'../Exp/Square.exp',50000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',2);
+md.hydrology=(hydrologydc);
+md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
+md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
+pos=find(md.mesh.x==0);
+md.hydrology.spcsediment_head(pos)=0.0;
+md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.timestepping.time_step=0;
+md.timestepping.final_time=1.0;
+md=solve(md,HydrologySolutionEnum());
+
+analitic=(md.mesh.x.^2-2*md.mesh.x*10^6)*(-2.0/(365*3600*24*2.0*md.hydrology.sediment_transmitivity));
+plotmodel(md,'data',md.results.HydrologySolution.SedimentHead-analitic)
+%plotmodel(md,'data',analitic)
Index: /issm/trunk/test/Par/GiaBenchmarksAB.par
===================================================================
--- /issm/trunk/test/Par/GiaBenchmarksAB.par	(revision 15396)
+++ /issm/trunk/test/Par/GiaBenchmarksAB.par	(revision 15396)
@@ -0,0 +1,72 @@
+%Geometry specific to Experiments A and B 
+rad=600000;
+nv=md.mesh.numberofvertices; 
+for i=1:nv,
+	dist=sqrt(md.mesh.x(i).^2+md.mesh.y(i)^2);
+	if (dist <= rad)
+		md.geometry.thickness(i)=2000.0;
+	else
+		md.geometry.thickness(i)=1.0; % non-zero thickness
+	end
+end
+md.geometry.thickness=md.geometry.thickness';
+md.geometry.bed=zeros(md.mesh.numberofvertices,1); 
+md.geometry.surface=md.geometry.thickness+md.geometry.bed; 
+
+%Ice density used for benchmarking, not 917 kg/m^3
+md.materials.rho_ice=1000; %kg m^3
+
+%GIA parameters specific to Experiments A  and B
+md.gia.mantle_viscosity=10^21*ones(md.mesh.numberofvertices,1);    %in Pa.s
+md.gia.lithosphere_thickness=100*ones(md.mesh.numberofvertices,1); %in km
+md.materials.lithosphere_shear_modulus=6.7*10^10;                  %in Pa
+md.materials.lithosphere_density=3.36;                             %in g/cm^3
+md.materials.mantle_shear_modulus=1.45*10^11;                      %in Pa
+md.materials.mantle_density=3.38;                                  %in g/cm^3
+
+
+%Initial velocity 
+x     = transpose(ncread('../Data/SquareSheetConstrained.nc','x'));
+y     = transpose(ncread('../Data/SquareSheetConstrained.nc','y'));
+vx    = transpose(ncread('../Data/SquareSheetConstrained.nc','vx'));
+vy    = transpose(ncread('../Data/SquareSheetConstrained.nc','vy'));
+index = transpose(ncread('../Data/SquareSheetConstrained.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
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+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.thermal.stabilization=1.;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.diagnostic.restol=0.05;
+md.steadystate.reltol=0.05;
+md.diagnostic.reltol=0.05;
+md.diagnostic.abstol=NaN;
+md.timestepping.time_step=1.;
+md.timestepping.final_time=3.;
+
+%Boundary conditions:
+md=SetIceSheetBC(md);
+
+%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/GiaBenchmarksCD.par
===================================================================
--- /issm/trunk/test/Par/GiaBenchmarksCD.par	(revision 15396)
+++ /issm/trunk/test/Par/GiaBenchmarksCD.par	(revision 15396)
@@ -0,0 +1,71 @@
+%Geometry specific to Experiments C and D  
+rad=800000;
+nv=md.mesh.numberofvertices; 
+for i=1:nv,
+	dist=sqrt(md.mesh.x(i).^2+md.mesh.y(i)^2);
+	if (dist <= rad)
+		md.geometry.thickness(i)=3000.0;
+	else
+		md.geometry.thickness(i)=1.0; % non-zero thickness
+	end
+end
+md.geometry.thickness=md.geometry.thickness';
+md.geometry.bed=zeros(md.mesh.numberofvertices,1); 
+md.geometry.surface=md.geometry.thickness+md.geometry.bed; 
+
+%Ice density used for benchmarking, not 917 kg/m^3
+md.materials.rho_ice=1000; %kg m^3
+
+%GIA parameters specific to Experiments A  and B
+md.gia.mantle_viscosity=10^21*ones(md.mesh.numberofvertices,1);    %in Pa.s
+md.gia.lithosphere_thickness=100*ones(md.mesh.numberofvertices,1); %in km
+md.materials.lithosphere_shear_modulus=6.7*10^10;                  %in Pa
+md.materials.lithosphere_density=3.32;                             %in g/cm^3
+md.materials.mantle_shear_modulus=1.45*10^11;                      %in Pa
+md.materials.mantle_density=3.34;                                  %in g/cm^3
+
+%Initial velocity 
+x     = transpose(ncread('../Data/SquareSheetConstrained.nc','x'));
+y     = transpose(ncread('../Data/SquareSheetConstrained.nc','y'));
+vx    = transpose(ncread('../Data/SquareSheetConstrained.nc','vx'));
+vy    = transpose(ncread('../Data/SquareSheetConstrained.nc','vy'));
+index = transpose(ncread('../Data/SquareSheetConstrained.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
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+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.thermal.stabilization=1.;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.diagnostic.restol=0.05;
+md.steadystate.reltol=0.05;
+md.diagnostic.reltol=0.05;
+md.diagnostic.abstol=NaN;
+md.timestepping.time_step=1.;
+md.timestepping.final_time=3.;
+
+%Boundary conditions:
+md=SetIceSheetBC(md);
+
+%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/ISMIPF.par
===================================================================
--- /issm/trunk/test/Par/ISMIPF.par	(revision 15395)
+++ /issm/trunk/test/Par/ISMIPF.par	(revision 15396)
@@ -45,2 +45,3 @@
 md.thermal.stabilization=1;
 md.thermal.penalty_threshold=10^5;
+md.transient.isthermal=0;
Index: /issm/trunk/test/Par/ISMIPF.py
===================================================================
--- /issm/trunk/test/Par/ISMIPF.py	(revision 15395)
+++ /issm/trunk/test/Par/ISMIPF.py	(revision 15396)
@@ -48,2 +48,3 @@
 md.thermal.stabilization=1
 md.thermal.penalty_threshold=10**5
+md.transient.isthermal=0
Index: /issm/trunk/test/Par/RoundSheetShelf.par
===================================================================
--- /issm/trunk/test/Par/RoundSheetShelf.par	(revision 15395)
+++ /issm/trunk/test/Par/RoundSheetShelf.par	(revision 15396)
@@ -107,4 +107,5 @@
 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.thermal.spctemperature=737.*ones(md.mesh.numberofvertices,1);
 
Index: /issm/trunk/test/Par/RoundSheetShelf.py
===================================================================
--- /issm/trunk/test/Par/RoundSheetShelf.py	(revision 15395)
+++ /issm/trunk/test/Par/RoundSheetShelf.py	(revision 15396)
@@ -116,4 +116,5 @@
 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.thermal.spctemperature=737.*numpy.ones((md.mesh.numberofvertices,1))
 
Index: /issm/trunk/test/Par/SquareSheetConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 15395)
+++ /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 15396)
@@ -49,4 +49,12 @@
 md.timestepping.final_time=3.;
 
+%GIA: 
+md.gia.lithosphere_thickness=100.*ones(md.mesh.numberofvertices,1); % in km
+md.gia.mantle_viscosity=1.0*10^21*ones(md.mesh.numberofvertices,1); % in Pa.s
+md.materials.lithosphere_shear_modulus=6.7*10^10;                   % in Pa
+md.materials.lithosphere_density=3.32;                              % in g/cm^-3
+md.materials.mantle_shear_modulus=1.45*10^11;                       % in Pa
+md.materials.mantle_density=3.34;                                   % in g/cm^-3
+
 %Boundary conditions:
 md=SetIceSheetBC(md);
Index: /issm/trunk/test/Par/SquareSheetConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 15395)
+++ /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 15396)
@@ -59,4 +59,12 @@
 md.timestepping.final_time=3.
 
+#GIA:
+md.gia.lithosphere_thickness=100.*numpy.ones((md.mesh.numberofvertices,1)); # in km
+md.gia.mantle_viscosity=1.*10**21*numpy.ones((md.mesh.numberofvertices,1)); # in Pa.s
+md.materials.lithosphere_shear_modulus=6.7*10**10;                          # in Pa
+md.materials.lithosphere_density=3.32;                                      # in g/cm^-3
+md.materials.mantle_shear_modulus=1.45*10**11;                              # in Pa
+md.materials.mantle_density=3.34;                                           # in g/cm^-3
+
 #Boundary conditions:
 md=SetIceSheetBC(md)
Index: /issm/trunk/test/Par/SquareShelf.py
===================================================================
--- /issm/trunk/test/Par/SquareShelf.py	(revision 15395)
+++ /issm/trunk/test/Par/SquareShelf.py	(revision 15396)
@@ -26,6 +26,5 @@
 vx=iVelF.variables['vx'][:]
 vy=iVelF.variables['vy'][:]
-index=iVelF.variables['index'][:].astype(float)
-index=reshape(index.T,(len(index),3),order='F')
+index=iVelF.variables['index'][:].astype(int)
 
 #dbg - begin
